Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R use value of a variable as a data frame column name

I am guessing this is simple for an experienced used...how can I use the value of a variable to assign it as a data frame column name? Say I have a simple data frame df as below, and a variable n that changes value based on user input. How could I insert a new data frame column which has as it's name the value of n? I would also ideally like to concatenate the value of n with a simple string. Thank you.

df<-data.frame(a=c(1,1,1),b=c(2,2,2))

  a b
1 1 2
2 1 2
3 1 2

When I simply try to assign a new column as

n<-15
df$n<-c(3,3,3)

the name of the column is simply n.

  a b n
1 1 2 3
2 1 2 3
3 1 2 3
like image 421
user2238328 Avatar asked Sep 04 '13 18:09

user2238328


People also ask

How do I convert column values to column names in R?

To convert a column values to column names, we can use dcast function of reshape2 package. For example, if we have a data frame called df that contains two columns say x and y, where x is categorical and y is numerical. Now if we want to convert the categories in x as column names then it can be done as dcast(df,y~x).

How do you name columns in data frames 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. The new name replaces the corresponding old name of the column in the data frame.

How do I create a data frame from a variable in R?

We can create a dataframe in R by passing the variable a,b,c,d into the data. frame() function. We can R create dataframe and name the columns with name() and simply specify the name of the variables.

Can you include an R list as a column of a data frame?

Now to add a list as a column, create a list with required values. Then, use the name of the data frame and the new column separated by $ and assign this to the list so created. This will assign the list to the column name given and then add it to the dataframe.


2 Answers

It's not the best idea to name a column with a number, but this will work:

df[,paste(n)] <- c(3,3,3)
like image 83
Señor O Avatar answered Oct 17 '22 11:10

Señor O


You could also do:

 df <- cbind(df,c(3,3,3))
 names(df)[ncol(df)] <- n

Although, as previously pointed out, it is not good practice to give numbers as column names.

like image 21
Mayou Avatar answered Oct 17 '22 12:10

Mayou