-1

I am trying to change the name of some columns in my data using str_c function ( after installing "stringr" package). Column names are as follow:

> x 
   a  b  c  d

I need to change the the "c" and "d" with "Aa" and "Ab". So instead of writing the full column names in my command, I will use the following structure:

colnames(x[,3:4])<-str_c(colnames(x[,1:2], "A")

However, the result shows the "A" at the end not the beginning of the name. So how to put the "A" at the beginning to get the following:

 > x
    a  b  Aa  Ab
mallet
  • 2,454
  • 3
  • 37
  • 64
  • 2
    You should document that `str_c` comes from a package that needs to be available and loaded. This question will not be helpful to someone who is just starting out in R and doesn't understand that this function is really just copying the base function `paste0`. It's also going to confuse them (and possibly you) when you go to use the `$` function and discover that it doesn't honor column names that begin with numerals unless the name is quoted. – IRTFM Jul 18 '14 at 16:57
  • @BondedDust all have been fixed – mallet Jul 18 '14 at 18:15

1 Answers1

0

If I understand your question and this is for displaying a "column name", then you should swap the order in your expression, this

colnames(x[,3:4])<-str_c(colnames(x[,1:2], "A")

should be

colnames(x[,3:4])<-str_c("A", colnames(x[,1:2])

Note column names with a leading digit won't work with the $ function unless the name is quoted. So "A" works fine with '$' function but "1" needs the name to be quoted.

mallet
  • 2,454
  • 3
  • 37
  • 64
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Yes it may work, but that doesn't mean it's a good idea. I think appropriate warnings should be given since `1a` is not a valid R name. – IRTFM Jul 18 '14 at 16:58
  • Sorry @Elliott maybe I missed something but I do not see how this could work. See http://stackoverflow.com/q/24867333/766828. – Beasterfield Jul 21 '14 at 14:44