我曾经这样做,使用group_by_
library(dplyr)
group_by <- c('cyl', 'vs')
mtcars %>% group_by_(.dots = group_by) %>% summarise(gear = mean(gear))
但现在group_by_
已弃用。我不知道如何使用整洁的评估框架来做到这一点。
将字符向量转换成符号列表并拼接进去
df %>% group_by(!!! syms(group_by))
有以下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))