Dplyr 非标准评估,函数名称作为字符串传递
Dplyr non standard evaluation with function name passed as a string
在使用 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 以便函数可以作为向量中的字符串传递?
我们可以使用get
和get
提取单个字符串的值。在这里,它是一个函数,所以它 returns 函数本身。
mtcars %>%
group_by(cyl) %>%
mutate(res= get(funs[1])(hp))
用于传递附加参数
mtcars$hp[1] <- NA
mtcars %>%
group_by(cyl) %>%
mutate(res= get(funs[1])(hp, na.rm = TRUE))
这些都使用 mutate
而不是 mutate_
mtcars %>%
group_by(cyl) %>%
mutate(res = do.call(funs[2], list(hp)))
mtcars %>%
group_by(cyl) %>%
mutate(res = match.fun(funs[2])(hp))
另请注意,如果我们使用 [[2]] 代替 [2],那么它们将适用于出现在问题中的字符向量 funs
以及 funs <- c(sum, mean)
.
在使用 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 以便函数可以作为向量中的字符串传递?
我们可以使用get
和get
提取单个字符串的值。在这里,它是一个函数,所以它 returns 函数本身。
mtcars %>%
group_by(cyl) %>%
mutate(res= get(funs[1])(hp))
用于传递附加参数
mtcars$hp[1] <- NA
mtcars %>%
group_by(cyl) %>%
mutate(res= get(funs[1])(hp, na.rm = TRUE))
这些都使用 mutate
而不是 mutate_
mtcars %>%
group_by(cyl) %>%
mutate(res = do.call(funs[2], list(hp)))
mtcars %>%
group_by(cyl) %>%
mutate(res = match.fun(funs[2])(hp))
另请注意,如果我们使用 [[2]] 代替 [2],那么它们将适用于出现在问题中的字符向量 funs
以及 funs <- c(sum, mean)
.