dplyr do()的非标准评估(NSE)

时间:2014-11-19 11:37:10

标签: r dplyr

我想实现像

这样的东西
mtcars %>% group_by(cyl) %>% do(mod = lm(mpg ~ disp, data = .))

在像这样的函数中

myfun <- function(d, groupvar, x, y) {
  d %>% group_by(groupvar) %>% do(mod = lm(y ~ x, data = .))
}
myfun(mtcars, cyl, disp, mpg)

但我无法理解NSE这么做。我知道,例如,像group_bysummarize这样的dplyr NSE函数具有关联的SE函数group_by_summarize_但似乎do没有关联do_

1 个答案:

答案 0 :(得分:2)

尝试

library(dplyr)
library(lazyeval)
f <- function(d, groupvar, x , y) {
    groupvar <- lazy(groupvar)
    x <- lazy(x)
    y <- lazy(y)
    d %>% group_by_(groupvar) %>%
        do(mod = lm(interp(quote(y ~ x), y = y, x = x), data = .))
}

f(mtcars, cyl, disp, mpg)
# Source: local data frame [3 x 2]
# Groups: <by row>
# 
#   cyl     mod
# 1   4 <S3:lm>
# 2   6 <S3:lm>
# 3   8 <S3:lm>