group_by by a vector of characters using tidy evaluation semantics

自闭症网瘾萝莉.ら 提交于 2020-01-15 11:07:46

问题


I used to do it, using group_by_

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

but now group_by_ is deprecated. I don't know how to do it using the tidy evaluation framework.


回答1:


There is group_by_at variant of group_by:

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

Above it's simplified version of generalized:

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

inside vars you could use any dplyr way of select variables:

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))



回答2:


Transform the character vector into a list of symbols and splice it in

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


来源:https://stackoverflow.com/questions/44984428/group-by-by-a-vector-of-characters-using-tidy-evaluation-semantics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!