Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 815
user2165857 Avatar asked Aug 06 '14 16:08

user2165857


People also ask

How do I create a new column of data in R?

1 Adding new columns. You can add new columns to a dataframe using the $ and assignment <- operators. To do this, just use the df$name notation and assign a new vector of data to it. As you can see, survey has a new column with the name sex with the values we specified earlier.

How do you add a column name in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector.

How do I add a column from one dataset to another in R?

How do I add a column to a DataFrame in R? To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values . Now, this will effectively add your new variable to your dataset.

Does mutate create a new column in R?

mutate() creates new columns that are functions of existing variables. It can also modify (if the name is the same as an existing column) and delete columns (by setting their value to NULL ).


1 Answers

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
like image 107
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 19 '22 16:09

A5C1D2H2I1M1N2O1R2T1