Reputation: 259
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
Upvotes: 6
Views: 16578
Reputation: 8818
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.
Upvotes: 2
Reputation: 17412
It's not the best idea to name a column with a number, but this will work:
df[,paste(n)] <- c(3,3,3)
Upvotes: 3