【问题标题】:passing column reference to group_by in an R function在 R 函数中将列引用传递给 group_by
【发布时间】:2016-01-22 07:41:58
【问题描述】:

这个问题与一个类似的帖子有关。 Function writing passing column reference to group_by

但是,我想将几​​个输入传递给使用 group_by_() 和 summarise_(​​) 的函数。

这是我的功能:

foo <- function(data,column,x1,x2){
    data %>%
            group_by_(.dots = column) %>%
            summarise_(.dots= c(~mean(x1), ~mean(x2)))
}

但是,当我跑步时

foo(mtcars,"cyl", "disp", "hp")

我收到以下错误。

Error in UseMethod("as.lazy_dots") : 
  no applicable method for 'as.lazy_dots' applied to an object of class "c('double', 'numeric')"
In addition: Warning message:
In mean.default(x1) : argument is not numeric or logical: returning NA

谁能告诉我哪里做错了?

【问题讨论】:

  • 我注意到您没有接受对您提出的任何问题的任何回答。尽管接受答案不是强制性的,但如果其中一个答案对您有用,那么这样做被认为是一种好的做法。这将为未来的读者提供有关解决方案价值的线索。另请参阅此帮助页面:What should I do when someone answers my question?

标签: r function group-by parameter-passing dplyr


【解决方案1】:

嗯,看起来您只是再次想要summarise_each,它确实有一个标准的评估替代方案summarise_each_。你可以把 foo 写成

foo <- function(data, column, x1, x2){
    data %>%
            group_by_(.dots = column) %>%
            summarise_each_(funs(mean), c(x1,x2))
}

并调用它

foo(mtcars,"cyl", "disp", "hp")
# Source: local data frame [3 x 3]
# 
#     cyl     disp        hp
#   (dbl)    (dbl)     (dbl)
# 1     4 105.1364  82.63636
# 2     6 183.3143 122.28571
# 3     8 353.1000 209.21429

【讨论】:

  • 哦,非常感谢大卫!我不知道我可以将特定变量传递给 summarise_each_ :)
猜你喜欢
  • 2015-12-13
  • 2021-01-19
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 2019-03-20
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多