string 在 R 中使用字符串名称分配 data.frame 的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10624067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign a column of a data.frame with string name in R
提问by mmann1123
I am trying to assign data to an existing dataframe with a name generated in a loop. A basic example might be
我正在尝试将数据分配给现有数据框,并使用循环中生成的名称。一个基本的例子可能是
A = data.frame(a = c(1,2,3), b=c(3,6,2))
for (i in 1:2){
name = paste("Name",i, sep="")
assign(name, c(6,3,2))
}
Now I just need to figure out how to add name1 and name2 to the data.frame A, while keeping their assigned name. I'm sure there is an easy answer, I'm just not seeing it right now.
现在我只需要弄清楚如何将 name1 和 name2 添加到 data.frame A,同时保留它们指定的名称。我敢肯定有一个简单的答案,只是我现在没有看到。
in the end I would like to end up with
最后我想结束
A
#a b name1 name2
#1 3 6 6
#2 6 3 3
#3 2 2 2
But I need to do this in an automated fashion.
但我需要以自动化的方式做到这一点。
For instance if the for loop could be adapted to be like
例如,如果 for 循环可以适应为
for (i in 1:2){
name = paste("Name",i, sep="")
assign(name, c(6,3,2)
A= cbind(A, get(paste(name,i,sep=""))) # works but doesn't maintain the column name as name1 or name2 etc
}
this however doesn't maintain column names
然而,这不维护列名
回答by Brian Diggs
The other answers are good, but if you are set on using a loop like you have, then this would work:
其他答案很好,但是如果您开始使用像您这样的循环,那么这将起作用:
A <- data.frame(a = c(1,2,3), b = c(3,6,2))
for (i in 1:2){
A[paste("Name", i, sep="")] <- c(6,3,2)
}
which gives
这使
> A
a b Name1 Name2
1 1 3 6 6
2 2 6 3 3
3 3 2 2 2
Alternatively, paste("Name", i, sep="")
could be replaced with paste0("Name", i)
或者,paste("Name", i, sep="")
可以替换为paste0("Name", i)
回答by Dirk Eddelbuettel
Maybe you want this:
也许你想要这个:
R> A <- data.frame(a=c(1,2,3), b=c(3,6,2))
R> colnames(A) <- paste("Names", 1:ncol(A), sep="")
R> A
Names1 Names2
1 1 3
2 2 6
3 3 2
R>
but as Tyler said in the comment, it is not entirely clear what you are asking.
但正如泰勒在评论中所说,你在问什么并不完全清楚。
回答by Tyler Rinker
Still not entirely sure what you're trying to accomplish:
仍然不完全确定您要完成的任务:
A = data.frame(a = c(1,2,3), b=c(3,6,2))
B <- data.frame(A, c(6, 3, 2), c(6, 3, 2))
names(B)[3:4] <- paste0("name", 1:2)
B
Which yields:
其中产生:
a b name1 name2
1 1 3 6 6
2 2 6 3 3
3 3 2 2 2