ah2*_*h25 3 group-by r function parameter-passing dplyr
这个问题与一篇类似的帖子有关.函数写入将列引用传递给group_by
但是,我想将几个输入传递给使用group_by_()和summarise_()的函数.
这是我的功能:
foo <- function(data,column,x1,x2){
data %>%
group_by_(.dots = column) %>%
summarise_(.dots= c(~mean(x1), ~mean(x2)))
}
Run Code Online (Sandbox Code Playgroud)
但是,当我跑
foo(mtcars,"cyl", "disp", "hp")
Run Code Online (Sandbox Code Playgroud)
我收到以下错误.
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
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?
嗯,看起来你只想summarise_each再次,它有一个标准的评估替代品,summarise_each_.你可以把foo写成
foo <- function(data, column, x1, x2){
data %>%
group_by_(.dots = column) %>%
summarise_each_(funs(mean), c(x1,x2))
}
Run Code Online (Sandbox Code Playgroud)
并称之为
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
Run Code Online (Sandbox Code Playgroud)