Joe
Joe

Reputation: 3806

using quosures within formula inside an anonymous function

I am trying to use quosures to pass along variable names within a custom function for data processing and use in a formula, but my use of quosures in the formula is not correct. Is there a better way to unquote arguments within a formula?

library(dplyr)
library(broom)
library(purrr)
library(tidyr)

foo <- function(mydata, dv, iv, group_var) {
  dv = enquo(dv)
  iv = enquo(iv)
  group_var = enquo(group_var)

  mydata <- mydata %>% 
    group_by(!!group_var) %>% 
    nest() 

  mydata %>% 
    mutate(model = map(data, 
      ~summary(lm(formula(substitute(dv ~ iv)), data = .))
    )) %>%         
    unnest(model %>% map(tidy))
}

foo(mydata=mtcars, dv=mpg, iv=wt, group_var=cyl)

My code produces "Error in mutate_impl(.data, dots) : Evaluation error: object is not a matrix."

This is a working version of code I am trying to make into a function:

mtcars %>% 
  group_by(cyl) %>% 
  nest() %>% 
  mutate(model = map(data, ~summary(lm(mpg ~ wt, data = .)))) %>% 
  unnest(model %>% map(tidy))

Upvotes: 4

Views: 910

Answers (1)

ngm
ngm

Reputation: 2589

You need to use base R nonstandard evaluation with functions like lm which are not "in the tidyverse" so to speak.

So you could change things to:

foo <- function(mydata, dv, iv, group_var) {
  flma <- as.formula(paste(substitute(dv), "~", substitute(iv)))
  group_var = enquo(group_var)

  mydata <- mydata %>% 
    group_by(!!group_var) %>% 
    nest() 

  mydata %>% 
    mutate(model = map(data, ~summary(lm(flma, data = .)))) %>%         
    unnest(model %>% map(tidy))
}   

foo(mtcars, mpg, wt, cyl)

That's fine if you know you are only doing simple regression. For more flexibility just pass the formula directly, as in:

foo2 <- function(mydata, flma, group_var) {
  group_var = enquo(group_var)

  mydata <- mydata %>% 
    group_by(!!group_var) %>% 
    nest() 

  mydata %>% 
    mutate(model = map(data, ~summary(lm(flma, data = .)))) %>%         
    unnest(model %>% map(tidy))
}   

foo(mtcars, mpg ~ wt, cyl)

Upvotes: 6

Related Questions