简体   繁体   中英

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

使用数字命名列不是最好的主意,但这可行:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM