Changing specific column names using pipe

Viewed 233

I want to change few specific column names of a data frame using dplyr's pipe. Below is one such example -

library(dplyr)
head(mtcars)

Now let say, I want to change 2nd and 3rd column names to "a" and "b" respectively. Trivially, I could do it as

colnames(mtcars)[2] <- "a"
colnames(mtcars)[3] <- "b"

However I want to do it using pipe and in a single line to enhance readability.

Any suggestion how should I do it?

Many thanks for your time.

3 Answers

With tidyverse, we can use rename_with

library(dplyr)
mtcars <- mtcars %>%
       rename_with(~ c('a', 'b'), 2:3)

names(mtcars)
#[1] "mpg"  "a"    "b"    "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"

We could use replace with names<-

head(mtcars) %>% 
     `names<-`(replace(names(.), 2:3, c('a', 'b')))

-output

#                   mpg a   b  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0 6 160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag     21.0 6 160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710        22.8 4 108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4 6 258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02  0  0    3    2
#Valiant           18.1 6 225 105 2.76 3.460 20.22  1  0    3    1

If you don't mind using data.table, then here is another option besides dplyr

setnames(as.data.table(mtcars), 2:3, c("a", "b"))[]

We could simply use select:

library(dplyr)
mtcars1 <- mtcars %>%
  select(1, a=2, b=3, everything())

Output:

> colnames(mtcars)
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
> colnames(mtcars1)
 [1] "mpg"  "a"    "b"    "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
Related