我想实现像
这样的东西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_by
或summarize
这样的dplyr NSE函数具有关联的SE函数group_by_
和summarize_
但似乎do
没有关联do_
。
答案 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>