group_by使用整齐的评估语义的字符向量

时间:2017-07-08 09:03:09

标签: r dplyr rlang nse

我过去常常使用group_by_

library(dplyr)
group_by <- c('cyl', 'vs')
mtcars %>% group_by_(.dots = group_by) %>% summarise(gear = mean(gear))

但现在不推荐使用group_by_。我不知道如何使用tidy evaluation framework

2 个答案:

答案 0 :(得分:8)

将字符向量转换为符号列表并将其拼接在

df %>% group_by(!!! syms(group_by))

答案 1 :(得分:3)

group_by_atgroup_by个变体:

library(dplyr)
group_by <- c('cyl', 'vs')
mtcars %>% group_by_at(group_by) %>% summarise(gear = mean(gear))

上面是广义的简化版本:

mtcars %>% group_by_at(vars(one_of(group_by))) %>% summarise(gear = mean(gear))

vars内,您可以使用任何dplyr方式来选择变量:

mtcars %>%
    group_by_at(vars(
        one_of(group_by) # columns from predefined set
        ,starts_with("a") # add ones started with a
        ,-hp # but omit that one
        ,vs # this should be always include
        ,contains("_gr_") # and ones with string _gr_
    )) %>%
    summarise(gear = mean(gear))