R: create a new column with a name coming from a variable

I have a data block with multiple columns and would like to add a new column and name it according to the previous variable. For example:

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

      

This is the part of the function in which the variable will change, and not every time by specifying:

df$C <- NA

      

I need one row that will accept "Variable" to name the additional column

+6


source to share


3 answers


Try [

instead $

:



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

      

+17


source


I am including additional information for the previous correct answer A5C1D2H2I1M1N2O1R2T1.

If you are trying to use a variable that is an integer then you will need to include as.character for this to work.

For example: df[, as.character(Variable)] <- NA



Otherwise, you will receive an error:

new columns will leave holes after existing columns

0


source


In the context of the data.frame name, also in a variable, this might be useful.

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

      

0


source







All Articles