我想在另一个函数中使用dplyr::group_by函数,但我不知道如何将参数传递给这个函数.

有人能提供一个有效的例子吗?

library(dplyr)
data(iris)
iris %.% group_by(Species) %.% summarise(n = n()) # 
## Source: local data frame [3 x 2]
##      Species  n
## 1  virginica 50
## 2 versicolor 50
## 3     setosa 50

mytable0 <- function(x, ...) x %.% group_by(...) %.% summarise(n = n())
mytable0(iris, "Species") # OK
## Source: local data frame [3 x 2]
##      Species  n
## 1  virginica 50
## 2 versicolor 50
## 3     setosa 50

mytable1 <- function(x, key) x %.% group_by(as.name(key)) %.% summarise(n = n())
mytable1(iris, "Species") # Wrong!
# Error: unsupported type for column 'as.name(key)' (SYMSXP)

mytable2 <- function(x, key) x %.% group_by(key) %.% summarise(n = n())
mytable2(iris, "Species") # Wrong!
# Error: index out of bounds

推荐答案

对于编程,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 2 Regroups现在不推荐使用,请改用groupby.

根据罗伯托的 comments ,在新版dplyr中,Update 3group_by_(list(...))现在变成group_by_(...).

Update 4在 comments 中增加了建议的微小变化.

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

Update 6:现在有一个{…}只有一个分组变量时使用的符号:

mytable <- function(x, group) {
  x %>% 
    group_by({{group}}) %>% 
    summarise(n = n())
}
mytable(iris, Species)

R相关问答推荐

基于R中的GPS点用方向箭头替换点

R创建一个数据透视表,计算多个组的百分比

以R中的正确顺序将日期时间字符列转换为posixct

从gtsummary包中使用tBL_strata()和tBL_summary()时删除变量标签

随机森林回归:下拉列重要性

次级y轴R gggplot2

derrr summarise每个组返回多行?

r替换lme S4对象的字符串的一部分

在R中使用download. file().奇怪的URL?

使用RSelenium在R中抓取Reddit时捕获多个标签

将标识符赋给事件序列,避免错误观察

如何使用同比折线图中的个别日

为R中的16组参数生成10000个样本的有效方法是什么?

Conditional documentr::R中数据帧的summarize()

快速合并R内的值

访问数据帧中未定义的列时出现R错误

为什么将负值向量提升到分数次方会得到NaN

注释不会绘制在所有ggplot2面上

R中的Desolve:返回的导数数错误

禁用时,SelecizeInput将变得不透明