开发者

add several variables to dataframe, based on vector

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 dat开发者_StackOverflow中文版a, 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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜