2

I have several similar data frames with many columns in common. I would like to select and rename a subset of those columns from any table.

library(tidyverse)
mtcars %>% 
select(my_mpg = mpg, 
       cylinders = cyl,
       gear)

Is it possible to do something like

my_select_rename <- c("my_mpg"="mpg","cylinders"="cyl","gear")

mtcars %>% 
   select_(.dots = my_select_rename)

but using the tidyeval framework instead?

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
Rickard
  • 3,600
  • 2
  • 19
  • 22

2 Answers2

1

I think you want:

my_select <- c("mpg","cyl","gear")
my_select_rename <- c("my_mpg","cylinders","gear")

mtcars %>% 
   select_at(vars(my_select)) %>%
   setNames(., my_select_rename)

                    my_mpg cylinders gear
Mazda RX4             21.0         6    4
Mazda RX4 Wag         21.0         6    4
Datsun 710            22.8         4    4
Hornet 4 Drive        21.4         6    3
Hornet Sportabout     18.7         8    3
CPak
  • 13,260
  • 3
  • 30
  • 48
0

lionel's answer to this question group_by by a vector of characters using tidy evaluation semantics provides the answer

mtcars %>% 
    select(!!! rlang::syms(my_select_rename))
Rickard
  • 3,600
  • 2
  • 19
  • 22