我过去常常使用group_by_
library(dplyr)
group_by <- c('cyl', 'vs')
mtcars %>% group_by_(.dots = group_by) %>% summarise(gear = mean(gear))
但现在不推荐使用group_by_
。我不知道如何使用tidy evaluation framework。
答案 0 :(得分:8)
将字符向量转换为符号列表并将其拼接在
中df %>% group_by(!!! syms(group_by))
答案 1 :(得分: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))