【问题标题】:errors when passing multiple arguments to dplyr functions in R将多个参数传递给 R 中的 dplyr 函数时出错
【发布时间】: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


【解决方案1】:

这确实有效:

UnFun <- function(dat, index) {
  dat %>%
    group_by_(.dots = c(quote(year), index)) %>%
    tally 
}
UnFun(dfx, c("areaA", "areaB"))

【讨论】:

  • 这似乎不起作用。我看到按年份和区域 A 分组的结果,但不是按区域 B 分组的结果。我想你想要dfx %&gt;% group_by_(.dots=c("year",other_vars)) %&gt;% tally 或者更简单的dfx %&gt;% count_(vars=c("year",other_vars))
  • 没问题。我认为您应该将答案编辑为可能的最佳/最清晰的版本。无需显示旧的、错误的部分或写“更正”、“编辑”等。
  • @Frank - 我不明白为什么 group_by_ 函数中需要“.dots”部分?另外,感谢您对计数功能的提醒 - 对我来说是新的
  • .dots部分的常用参考在这里:cran.r-project.org/web/packages/dplyr/vignettes/nse.html我自己没看过,只是盲目使用:)
猜你喜欢
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多