【发布时间】:2023-04-01 12:48:01
【问题描述】:
扩展@G 给出的this answer。格洛腾迪克,如何在一个函数中将多个分组变量传递给 dplyr?
假设我有这些数据:
# Data
set.seed(1)
dfx <- data.frame(nLive = sample(x = 10, size = 40, replace = TRUE),
nDead = sample(x = 3, size = 40, replace = TRUE),
areaA = c(rep("A", 20), rep("B", 20)),
areaB = rep( c( rep("yes", 10), rep("no", 10)), 2),
year = rep(c(2000,2002,2004,2006,2008),4)
)
我想按年份分组,最多可能还有 2 个其他变量。
G. Grothendieck 的示例非常适合指定 1 个索引:
UnFun <- function(dat, index) {
dat %>%
group_by(year) %>%
regroup(list(index)) %>%
summarise(n = n() )
}
> UnFun(dfx, "areaA")
Source: local data frame [2 x 2]
areaA n
1 A 20
2 B 20
> UnFun(dfx, "areaB")
Source: local data frame [2 x 2]
areaB n
1 no 20
2 yes 20
但当我尝试按两者(或仅按年份)分组时,我得到错误或错误答案:
> UnFun(dfx, list("areaA", "areaB"))
Error: cannot convert to symbol (SYMSXP)
> UnFun(dfx, c("areaA", "areaB"))
Source: local data frame [2 x 2]
areaA n
1 A 20
2 B 20
UnFun(dfx, NULL)
Error: cannot convert to symbol (SYMSXP)
关于如何正确指定 0、1 或 2 组选项的任何提示?
感谢 R 社区!
【问题讨论】:
-
对您链接到的答案的第二条评论显示了两种似乎可行的方法。看起来您需要在函数中使用
...而不是index或使用regroup(as.list(index))而不是regroup(list(index))。 -
@aosmith,感谢您的帮助!这是一个简单的解决方法:)
标签: r arguments user-defined-functions dplyr