在使用dplyr
管道时,我想将一个函数传递给mutate
使用NSE
从向量传递的函数名。
例子
给定两个函数名称的向量:
funs <- c("sum", "mean")
我想使用第一个值来获得总和:
require(dplyr)
mtcars %>%
group_by(cyl) %>%
mutate_(res = funs[1](hp))
这会导致错误:
Error in as.lazy_dots(list(...)) : attempt to apply non-function
do.call
do.call
基于解决方案似乎为总和产生了一些结果:
mtcars %>%
group_by(cyl) %>%
mutate_(res = do.call(funs[1], .))
但尝试使用时失败mean
:
>> mtcars %>%
+ group_by(cyl) %>%
+ mutate_(res = do.call(funs[2], .))
Error in mean.default(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, :
argument "x" is missing, with no default
我猜它在这里的应用方式根本没有意义。因此我的问题是:如何使用nse indplyr
以便函数可以作为字符串从向量传递?