Dplyr非标准评估,函数名称作为字符串

时间:2016-12-02 15:30:10

标签: r function dplyr scoping nse

在使用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

我猜测它在这里的应用方式毫无意义。因此,我的问题是:如何在dplyr中使用,以便函数可以作为字符串从向量传递?

2 个答案:

答案 0 :(得分:3)

我们可以使用getget提取单个字符串的值。这里,它是一个函数,因此它返回函数本身。

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))

答案 1 :(得分:2)

这些都使用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)