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