Andreas
Andreas

Reputation: 6738

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 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

Upvotes: 2

Views: 3741

Answers (2)

Marek
Marek

Reputation: 50734

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

Upvotes: 3

Etienne Racine
Etienne Racine

Reputation: 1373

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

Upvotes: 3

Related Questions