1

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.

Frank
  • 66,179
  • 8
  • 96
  • 180
kRazzy R
  • 1,561
  • 1
  • 16
  • 44

1 Answers1

3

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"
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • thanks a lot. I just wanted to know , how to apply the above solution selectively to columns of my choice? for instance if I wanted to arrive at an output like this `"Column1.Apple" "Column2" "Column3" "Column4.Banana" ` – kRazzy R Nov 17 '15 at 22:52
  • 1
    @kRazzyR - subset your columns as appropriate. `colnames(x)[c(1,4)] <- make.names(paste(names(x)[c(1,4)], c(A,B) ))` – thelatemail Nov 17 '15 at 23:34