对于编程来说,group_by_
是对应于group_by
:
library(dplyr)
mytable <- function(x, ...) x %>% group_by_(...) %>% summarise(n = n())
mytable(iris, "Species")
# or iris %>% mytable("Species")
这使:
Species n
1 setosa 50
2 versicolor 50
3 virginica 50
Update在写这篇文章时,使用了 dplyr%.%
这是上面最初使用的,但现在%>%
受到青睐,因此对上面的内容进行了更改以保持相关性。
Update 2regroup 现已弃用,请使用 group_by_ 代替。
Update 3 group_by_(list(...))
现在变成group_by_(...)
根据罗伯托的评论,在新版本的 dplyr 中。
Update 4添加了评论中建议的微小变化。
更新5:使用 rlang/tidyeval 现在可以做到这一点:
library(rlang)
mytable <- function(x, ...) {
group_ <- syms(...)
x %>%
group_by(!!!group_) %>%
summarise(n = n())
}
mytable(iris, "Species")
或路过Species
未评估,即周围没有引号:
library(rlang)
mytable <- function(x, ...) {
group_ <- enquos(...)
x %>%
group_by(!!!group_) %>%
summarise(n = n())
}
mytable(iris, Species)
更新6:现在有一种 {{...}} 表示法可以在只有一个分组变量的情况下使用:
mytable <- function(x, group) {
x %>%
group_by({{group}}) %>%
summarise(n = n())
}
mytable(iris, Species)