2016-10-28 123 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()函数插入它,正如我在原始问题中所做的那样?还是不可能这样做? –