r - 在 R 函数中将列引用传递给 group_by

标签 r function group-by parameter-passing dplyr

这个问题与类似的帖子有关。 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

谁能告诉我哪里做错了?

最佳答案

好吧,看起来您只需要再次使用 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

关于r - 在 R 函数中将列引用传递给 group_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33291002/

相关文章:

r - 混合模型/lsmeans 结果的线图(使用 ggplot?)

r - 将百分比标签添加到堆叠条形图

c# - 在文本框中添加数字

python - Pandas 数据框获取每组的第一行

r - 将摘要转换为data.frame

r - 用 dplyr 按组计算平均值

javascript - 如何访问symfony2中另一个html.twig文件中的javascript函数?

python - pep 232 也适用于实例方法吗?

sql - 查找所有共同作者 - 多对多映射表的分面/分组

ruby-on-rails - 在 ActiveRecord 中按 created_at 对记录进行分组