基于向量向数据框添加多个变量
我确信这很容易 - 但我现在无法弄清楚。
基本上:我有一个很长的变量向量:
names <- c("first","second", "third")
我有一些数据,现在需要添加变量。我可以这样做:
data$first <- NA
但由于我有一个很长的清单,而且我想要一个自动化的解决方案。 这不起作用。
for (i in 1:length(names)) (paste("data$", names[i],sep="") <- NA)
我想要这个的原因是我需要垂直合并到数据帧,其中没有应有的所有变量。
提前致谢
I am sure this is easy - but I can't figure it out right now.
Basically: I have a long vector of variables:
names <- c("first","second", "third")
I have some data, and I now need to add the variables. I could do:
data$first <- NA
But since I have a long list, and I would like an automated solution. This doesn't work.
for (i in 1:length(names)) (paste("data$", names[i],sep="") <- NA)
The reason I want this, is that I need to vertically merge to dataframes, where one doesn't have all the variables it should have.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过使用括号而不是 $ 来访问使用名称变量的列。
但是你可以看看 reshape 包(或 plyr)中的 rbind.fill() 。
希望这有帮助,
艾蒂安
You can access column using a variable for the name by using brackets instead of $.
But you could take a look at rbind.fill() in the reshape package (or plyr).
Hope this helps,
Etienne
正如您在示例中看到的,
不需要循环,您只需执行
示例即可:
As you can see in examples to
there is no need to loop, you can just do
Example: