0

I would like to change the column names of my 4th and 5th column with this code, but it is not working.

colnames(df[,4:5]) <- paste(colnames(df[,4:5]), "13", sep= "_")

It works if I remove [,4:5] and change the column names for the whole data frame.

colnames(df) <- paste(colnames(df), "13", sep= "_")

but my desired output is just to change the 4th and 5th column. Thanks.

neilfws
  • 32,751
  • 5
  • 50
  • 63
kaix
  • 305
  • 3
  • 10

2 Answers2

3

It is much easier to do with dplyr::rename().

Simply use df %>% rename(new_name = old_name), and you're done!

Here is an example

library(dplyr)
head(mtcars, n = 2)
              mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4

mtcars_new = mtcars %>% rename(new_mpg = mpg)

head(mtcars_new, n = 2)
              new_mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4          21   6  160 110  3.9 2.620 16.46  0  1    4    4
Mazda RX4 Wag      21   6  160 110  3.9 2.875 17.02  0  1    4    4
mhovd
  • 3,724
  • 2
  • 21
  • 47
0

You can try replace like below

setNames(df, replace(names(df), 4:5, paste(names(df)[4:5], "13", sep = "_")))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81