tags:

views:

80

answers:

2

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

+2  A: 

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

Etiennebr
Perfect - thank you Etiennebr!!! - It works
Andreas
rbind.fill is great.
Eduardo Leoni
+1  A: 

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
Marek
Thank you Marek. This is a strictly speaking a better answer then Etiennebr. But she did give rbind.fill - and was fast. So I have accepted her answer. But I keep learning :-)
Andreas