基于向量向数据框添加多个变量

发布于 2024-08-29 02:54:18 字数 410 浏览 3 评论 0原文

我确信这很容易 - 但我现在无法弄清楚。

基本上:我有一个很长的变量向量:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怎会甘心 2024-09-05 02:54:18

您可以通过使用括号而不是 $ 来访问使用名称变量的列。

for (name in names) data[name] <- NA

但是你可以看看 reshape 包(或 plyr)中的 rbind.fill() 。

希望这有帮助,
艾蒂安

You can access column using a variable for the name by using brackets instead of $.

for (name in names) data[name] <- NA

But you could take a look at rbind.fill() in the reshape package (or plyr).

Hope this helps,
Etienne

网名女生简单气质 2024-09-05 02:54:18

正如您在示例中看到的,

?`[<-.data.frame`

不需要循环,您只需执行

data[names] <- NA

示例即可:

> (data <- data.frame(x=1:3, y=letters[1:3]))
  x y
1 1 a
2 2 b
3 3 c
> data[names] <- NA
> data
  x y first second third
1 1 a    NA     NA    NA
2 2 b    NA     NA    NA
3 3 c    NA     NA    NA

As you can see in examples to

?`[<-.data.frame`

there is no need to loop, you can just do

data[names] <- NA

Example:

> (data <- data.frame(x=1:3, y=letters[1:3]))
  x y
1 1 a
2 2 b
3 3 c
> data[names] <- NA
> data
  x y first second third
1 1 a    NA     NA    NA
2 2 b    NA     NA    NA
3 3 c    NA     NA    NA
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文