在本文中,我們將討論如何在 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。