0

I'd like to group my data, then build two linear models per group, gather the results, and use broom to summarize the model parameters, but I'm having an infinite recursion error that I cant seem to understand. Here's the code:

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

mtcars %>% 
group_by(am) %>% 
dplyr::do(simple_fit =  lm(mpg ~ disp, data = .), 
          complex_fit = lm(mpg ~ disp + hp, data = .)) %>% 
ungroup()
gather(model_type, model, -am) %>% 
broom::tidy(model)

which results in this error:

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

There are only 4 models in this example, so I don't understand why I'm hitting such a deep nested loop?

JJJ
  • 1,009
  • 6
  • 19
  • 31
kmace
  • 1,994
  • 3
  • 23
  • 39

1 Answers1

2

I found a comment on the github that fixed my issue here

Fixed version of the code is as follows:

mtcars %>% 
group_by(am) %>% 
dplyr::do(simple_fit = lm(mpg~disp, data = .), 
          complex_fit = lm(mpg ~ disp + hp, data = .)) %>% 
ungroup() %>% 
gather(model_type, model, -am) %>% 
rowwise() %>% 
broom::tidy(model)
kmace
  • 1,994
  • 3
  • 23
  • 39