我是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"
我種出來的想法,所以如果有人可以請給我一個解釋什麼是錯的,爲什麼,以及如何解決它,我將不勝感激。謝謝!
我不知道我是否正確理解你。你能分享一個代表你的「mytable」的小型可重複使用的例子嗎? –