我是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”的小型可重复使用的例子吗? –