在本文中,我们将讨论如何在 R 中将数据帧转换为向量。对于将数据帧转换为向量,我们可以简单地将数据帧列名称传递为 [[index]]。
方法:
我们在 DataFrame 中取一列,并通过选择方法将其传递给另一个变量。选择方法可以定义为使用“[[]]”从 DataFrame 中选择一列。
- 创建 DataFrame
- 对创建的 DataFrame 中的列应用选择过程。
- 验证结果变量。
用法:
convert_data = dataframe_name[[‘column_name’]]
下面给出了使用这种方法来产生这个函数的实现。
范例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)
输出:
范例2:
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)
输出:
相关用法
- R语言 as.vector()用法及代码示例
- R Named Vector转DataFrame用法及代码示例
- R语言 is.vector()用法及代码示例
- R语言 toString()用法及代码示例
- R语言 as.factor()用法及代码示例
- R语言 as.logical()用法及代码示例
注:本文由纯净天空筛选整理自sravankumar8128大神的英文原创作品 Convert DataFrame to vector in R。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。