📜  将 DataFrame 转换为 R 中的向量

📅  最后修改于: 2022-05-13 01:55:34.386000             🧑  作者: Mango

将 DataFrame 转换为 R 中的向量

在本文中,我们将讨论如何在 R 中将数据帧转换为向量。对于将数据帧转换为向量,我们可以简单地将数据帧列名称作为 [[index]] 传递。

方法:

我们正在数据框中获取一列,并通过选择方法将其传递给另一个变量。选择方法可以定义为使用“[[]]”从数据框中选择一列。

  • 创建数据框
  • 在创建的数据框中的列上应用选择过程。
  • 验证结果变量。

句法:

下面给出了使用这种方法来产生这个功能的实现。

示例 1:

R
# creating a vector for names
names=c('sravan','bobby','ojaswi','gnanesh','rohith','satwik')
  
# creating vector for marks 1
marks1=c(96,76,82,89,100,94)
  
# creating vector for marks 2
marks2=c(98,79,98,78,98,89)
  
# display all details
print(names)
print(marks1)
print(marks2)
print("----------------------")
  
# passing vectors to the data frame
Final_data = data.frame(names,marks1,marks2)
  
# display data frame
print(Final_data)
print("-------------------conversion---------------------")
  
# converting marks1 dataframe column into vector
# by passing as index
convert_data1 = Final_data[['marks1']]
print(convert_data1)
  
# converting marks2 dataframe column into vector 
# by passing as index
convert_data2 = Final_data[['marks2']]
print(convert_data2)


R
# creating a vector for subjects
subjects=c('java','python','c/c++')
  
# creating vector for teachers
teachers=c('ravi','swapna','sai')
  
# creating vector for pass percentage
pass=c(98.11,90.45,95)
  
# display all details
print(subjects)
print(teachers)
print(pass)
print("----------------------")
  
# passing vectors to the data frame
Final_data = data.frame(subjects,teachers,pass)
  
# display data frame
print(Final_data)
print("-------------------conversion---------------------")
  
# converting subjects dataframe column into 
# vector by passing as index
convert_data1 = Final_data[['subjects']]
print(convert_data1)
  
# converting teachers dataframe column into 
# vector by passing as index
convert_data2 = Final_data[['teachers']]
print(convert_data2)
  
# converting pass dataframe column into vector
# by passing as index
convert_data2 = Final_data[['pass']]
print(convert_data2)


输出:

示例 2:

电阻

# creating a vector for subjects
subjects=c('java','python','c/c++')
  
# creating vector for teachers
teachers=c('ravi','swapna','sai')
  
# creating vector for pass percentage
pass=c(98.11,90.45,95)
  
# display all details
print(subjects)
print(teachers)
print(pass)
print("----------------------")
  
# passing vectors to the data frame
Final_data = data.frame(subjects,teachers,pass)
  
# display data frame
print(Final_data)
print("-------------------conversion---------------------")
  
# converting subjects dataframe column into 
# vector by passing as index
convert_data1 = Final_data[['subjects']]
print(convert_data1)
  
# converting teachers dataframe column into 
# vector by passing as index
convert_data2 = Final_data[['teachers']]
print(convert_data2)
  
# converting pass dataframe column into vector
# by passing as index
convert_data2 = Final_data[['pass']]
print(convert_data2)

输出: