【发布时间】:2017-04-17 13:42:09
【问题描述】:
在使用dplyr 管道时,我想使用NSE 将函数传递给mutate,函数名称是从向量传递的。
示例
给定两个函数名的向量:
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 的解决方案似乎为 sum 生成了一些结果:
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
我猜它在这里的应用方式根本没有意义。因此我的问题是:如何在dplyr 中使用nse,以便函数可以作为字符串从向量传递?
【问题讨论】:
标签: nse r function dplyr scoping nse