1

I have a data frame, that I filter, drop and add some columns and than I would like to rename all of columns, all using pipes (%>%).

However, I don't understand how to take a current colnames vector (within %>%) and replace it with another vector? If I would not drop columns, it seems pretty easy, but how to "update" the vector of colnames within a chain of pipes?

library(dplyr)
library(tidyr)

data("mtcars")

mtcars %>% 
  filter(disp < 200) %>% 
   dplyr::select(-c('mpg','cyl', "disp")) %>%
   mutate(Type = 2)  %>% 
  # rename_at(vars(names(df),              # how to rename the columns??? 
   #          function(x) paste(names(df), "new", sep = "_"))) %>% 
   head(2)

What I get:

   hp drat    wt  qsec vs am gear carb Type
1 110  3.9 2.620 16.46  0  1    4    4    2
2 110  3.9 2.875 17.02  0  1    4    4    2

What I expect (changed colnames)

hp_new drat_new    wt_new  qsec_new vs_new am_new gear_new carb_new Type_new
1 110     3.9      2.620   16.46     0      1      4        4         2
2 110     3.9      2.875   17.02     0      1      4        4         2
Sotos
  • 51,121
  • 6
  • 32
  • 66
maycca
  • 3,848
  • 5
  • 36
  • 67

2 Answers2

6

We can use rename_all

library(dplyr)

mtcars %>% 
  filter(disp < 200) %>% 
  dplyr::select(-c('mpg','cyl', "disp")) %>%
  mutate(Type = 2)  %>%
  rename_all(~paste0(., "_new")) %>% head

#  hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new Type_new
#1    110     3.90  2.620    16.46      0      1        4        4        2
#2    110     3.90  2.875    17.02      0      1        4        4        2
#3     93     3.85  2.320    18.61      1      1        4        1        2
#4     62     3.69  3.190    20.00      1      0        4        2        2
#5     95     3.92  3.150    22.90      1      0        4        2        2
#6    123     3.92  3.440    18.30      1      0        4        4        2
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

We can use rename_all with str_c (tidyverse approach)

library(dplyr)
library(stringr)

mtcars %>% 
  filter(disp < 200) %>% 
  dplyr::select(-c('mpg','cyl', "disp")) %>%
  mutate(Type = 2)  %>% 
  rename_all(~ str_c(., "_new")) %>%
  head(2)
#  hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new Type_new
#1    110      3.9  2.620    16.46      0      1        4        4        2
#2    110      3.9  2.875    17.02      0      1        4        4        2

Or another option is set_names

mtcars %>% 
  filter(disp < 200) %>% 
  dplyr::select(-c('mpg','cyl', "disp")) %>% 
  mutate(Type = 2)  %>% 
  set_names(str_c(names(.), "_new"))

Or using base R

nm1 <-  setdiff(names(mtcars), c("mpg", "cyl", "disp"))
setNames(subset(mtcars, disp < 200, select = nm1), paste0(nm1, "_new"))
akrun
  • 874,273
  • 37
  • 540
  • 662