选择并重命名存储在变量

时间:2017-07-13 14:16:36

标签: r dplyr rlang tidyeval

我有几个相似的数据框,有许多共同的列。我想从任何表中选择并重命名这些列的子集。

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

是否可以执行类似

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

mtcars %>% 
   select_(.dots = my_select_rename)

但是改为使用tidyeval框架?

2 个答案:

答案 0 :(得分:1)

我想你想要:

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

答案 1 :(得分:0)

lionel对此问题的回答group_by by a vector of characters using tidy evaluation semantics提供了答案

mtcars %>% 
    select(!!! rlang::syms(my_select_rename))