2016-10-28 125 views
-2

我是R新手,我試圖在for循環中創建引用矢量的變量,其中循環的索引將被附加到變量名稱中。然而,下面的代碼,我試圖插入新的向量到大數據框中的適當位置,不工作,我嘗試了許多變種的get(),as.vector(),eval( )等在數據框架構造函數中。爲R中的向量動態分配變量名稱?

我希望num_incorrect.8和num_incorrect.9成爲值爲0的向量,然後插入到mytable中。

cols_to_update <- c(8,9) 

for (i in cols_to_update) 
{ 
#column name of insertion point 
insertion_point <- paste("num_correct",".",i,sep="") 
#create the num_incorrect col -- as a vector of 0s 
assign(paste("num_incorrect",".",i,sep=""), c(0)) 

#index of insertion point 
thespot <- which(names(mytable)==insertion_point) 
#insert the num_incorrect vector and rebuild mytable 
mytable <- data.frame(mytable[1:thespot], as.vector(paste("num_incorrect",".",i,sep="")), mytable[(thespot+1):ncol(mytable)]) 
#update values 
mytable[paste("num_incorrect",".",i,sep="")] <- mytable[paste("num_tries",".",i,sep="")] - mytable[paste("num_correct",".",i,sep="")] 
} 

當我看着柱插入如何去,它看起來像這樣:

[626] "num_correct.8"           
[627] "as.vector.paste..num_incorrect........i..sep........2" 
... 
[734] "num_correct.9"           
[735] "as.vector.paste..num_incorrect........i..sep........3" 

基本上,它看起來像它採取我的命令作爲文字文本。的最後一行代碼按預期工作,並在數據幀的末尾創建新的列(自收到線沒有插入列到合適的位置):

[1224] "num_incorrect.8"          
[1225] "num_incorrect.9" 

我種出來的想法,所以如果有人可以請給我一個解釋什麼是錯的,爲什麼,以及如何解決它,我將不勝感激。謝謝!

+0

我不知道我是否正確理解你。你能分享一個代表你的「mytable」的小型可重複使用的例子嗎? –

回答

0

錯誤發生在代碼的第二行,不包括創建向量並將其添加到數據框中的註釋。

你只需要添加矢量並更新名稱。您可以刪除assign函數,因爲它不會創建矢量,而只是將值0賦值給變量。

而不是你的代碼的第二行代碼放在下面的代碼,它應該工作。

#insert the vector at the desired location 
mytable <- data.frame(mytable[1:thespot], newCol = vector(mode='numeric',length = nrow(mytable)), mytable[(thespot+1):ncol(mytable)]) 

#update the name of new location 
names(mytable)[thespot + 1] = paste("num_incorrect",".",i,sep="") 
+0

謝謝你的回答;你的建議奏效了。然而,如果我想這樣做: 指定(粘貼(「準確」,「。」,我,我如何引用vector並使用data.frame()函數插入它,正如我在原始問題中所做的那樣?還是不可能這樣做? –