R uses the value of the variable as the column name of the data frame

I assume this is just for trial use ... how can I use the value of a variable to designate it as the column name of the data frame? Let's say I have a simple df data frame, as shown below, and a variable n that changes the value based on user input. How can I insert a new column of data frames that has the name n? I would also ideally like to combine the value of n with a simple string. Thanks.

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

When I just try to assign a new column as

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

the column name is just n.

  abn 1 1 2 3 2 1 2 3 3 1 2 3 
+6
source share
2 answers

It is not a good idea to name a column with a number, but this will work:

 df[,paste(n)] <- c(3,3,3) 
+3
source

You can also do:

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

Although, as mentioned earlier, it is not recommended to specify numbers as column names.

+2
source

Source: https://habr.com/ru/post/953187/


All Articles