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
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).
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.
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.
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.
It's not the best idea to name a column with a number, but this will work:
df[,paste(n)] <- c(3,3,3)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With