kRazzy R
kRazzy R

Reputation: 1589

how to append names to " column names" of the output data frame in R?

i know that i can change the names of columns using

colnames(x)<-c("Column1" , "Column 2" ,"Column 3", "Column 4")

If I have

A<-"Apple"  
B<-"Banana"  

What should I do so that the names of the output data frame will have names like this

"Column 1 Apple" "Column 2 Banana" "Column 3 Apple" "Column 4 Banana"

I have looked at Replace "names" of columns of a data frame with different (new) names in another file in R
and
How to dynamically assign names to dataframes?
But I didn't quite understand how to apply it to my case.

Upvotes: 1

Views: 379

Answers (1)

thelatemail
thelatemail

Reputation: 93938

Just use paste and rely on the fact that R recycles vectors. As @Richard noted, you should avoid spaces in column/variable names to make your life easier. make.names can take care of that:

make.names(paste(names(x), c(A,B)))
#[1] "Column1.Apple"  "Column2.Banana" "Column3.Apple"  "Column4.Banana"

Upvotes: 3

Related Questions