danilinares
danilinares

Reputation: 1270

Non standard evaluation (NSE) for dplyr do()

I would like to implement something like

mtcars %>% group_by(cyl) %>% do(mod = lm(mpg ~ disp, data = .))

inside a function like this

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

but I cannot understand well enough NSE to do it. I know, for example, that dplyr NSE functions like group_by or summarize have the associated SE functions group_by_ and summarize_ but it seems that do has not an associated do_.

Upvotes: 0

Views: 393

Answers (1)

konvas
konvas

Reputation: 14346

Try

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>

Upvotes: 2

Related Questions