我有一个名为mergedColors
的颜色列表。从这个颜色列表中,我使用for()
循环来创建一个与每种独特颜色相对应的矩阵。到目前为止,一切正常。然后,我想在最初创建矩阵后继续更改/编辑循环中的矩阵。在示例中,我尝试更改第三列的名称。但是,我并不完全确定如何去做。当我尝试通过我用来创建它们的相同语法来调用它们时,
colnames(paste("merged",each,sep="_"))[3] = "Temp"
R返回错误:"赋值目标扩展为非语言对象"。如何在循环内部调用我刚刚创建的矩阵?
示例数据:
mergedColors = c("red", "blue", "green", "red", "black", "blue", "blue", "green", "yellow", "red")
table(mergedColors)
for(each in unique(mergedColors)){
assign(paste("merged",each,sep="_"), as.matrix(cbind(cars, c(each))))
#colnames(paste("merged",each,sep="_"))[3] = "Temp"
}
答案 0 :(得分:2)
您只需要使用get
告诉R您要粘贴的内容是指对象。
像这样:
tmp <- get(paste("merged",each,sep="_"))
colnames(tmp)[3] = "Temp"
> head(tmp)
speed dist Temp
[1,] " 4" " 2" "yellow"
[2,] " 4" " 10" "yellow"
[3,] " 7" " 4" "yellow"
[4,] " 7" " 22" "yellow"
[5,] " 8" " 16" "yellow"
[6,] " 9" " 10" "yellow"
这是完整循环:
for(each in unique(mergedColors)){
assign(paste("merged",each,sep="_"), as.matrix(cbind(cars, c(each))))
#colnames(paste("merged",each,sep="_"))[3] = "Temp"
tmp <- get(paste("merged",each,sep="_"))
colnames(tmp)[3] = "Temp"
assign(paste("merged",each,sep="_"), tmp)
}