user2165857
user2165857

Reputation: 2690

R: create new column with name coming from variable

I have a dataframe with several columns and would like to add a new column and name it according to a previous variable. For example:

df <- data.frame("A" = c(1, 2, 3, 4), "B" = c("a", "c", "d", "b"))
Variable <- "C"

This is part of a function where the variable will be changing and rather than each time specifying:

df$C <- NA

I would like a one line that will take the "Variable" to name the additional column

Upvotes: 22

Views: 43580

Answers (2)

Ferroao
Ferroao

Reputation: 3033

In the context of a data.frame name also taken in a variable this might be helpful.

df <- data.frame("A" = c(1, 2, 3, 4), "B" = c("a", "c", "d", "b") )
Variable<-"C"
dfname<-"df"
df<-within ( assign(dfname  , get(dfname) ),
             assign(Variable, NA          )
           )

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

Try [ instead of $:

> df[, Variable] <- NA
> df
  A B  C
1 1 a NA
2 2 c NA
3 3 d NA
4 4 b NA

Upvotes: 36

Related Questions