1

我曾经这样做,使用group_by_

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

但现在group_by_已弃用。我不知道如何使用整洁的评估框架来做到这一点。

4

2 回答 2

9

将字符向量转换成符号列表并拼接进去

df %>% group_by(!!! syms(group_by))
于 2017-07-10T08:40:45.420 回答
3

有以下group_by_at变体group_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))
于 2019-03-08T10:54:13.920 回答