Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing specific column names using pipe [duplicate]

Tags:

r

dplyr

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.

like image 269
Brian Smith Avatar asked Mar 19 '26 13:03

Brian Smith


1 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
like image 173
akrun Avatar answered Mar 22 '26 02:03

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!