Augment predictions from many models in the original dataset

Viewed 164

I want to run many models with all possible combinations of x and ys. I created the following code to do that.

library(tidyverse)

y <- names(mtcars)

xs <- map(y, ~setdiff(names(mtcars), .x)) %>% 
  map(~paste0(.x, collapse = "+")) %>%
  unlist()

ys <- names(mtcars)

models <- tibble(ys, xs) %>%
  mutate(Formula = paste0(ys, " ~ ", xs)) %>% 
  mutate(model = map(Formula, ~glm(as.formula(.x), data = mtcars)))

Now, I want to get all the predictions from all these models in the original dataset, here mtcars. How can I do that? Is there a way to use augment from broom?

1 Answers

You can use map and augment similar to the way you fit glm to each row.

library(tidyverse)
library(broom)

y <- names(mtcars)

xs <- map(y, ~setdiff(names(mtcars), .x)) %>% 
  map(~paste0(.x, collapse = "+")) %>%
  unlist()

ys <- names(mtcars)

models <- tibble(ys, xs) %>%
  mutate(Formula = paste0(ys, " ~ ", xs)) %>% 
  mutate(model = map(Formula, ~glm(as.formula(.x), data = mtcars))) %>%
  mutate(Pred = map(model, augment))

The prediction is in the .fitted column in each dataframe from the Pred list.

models2 <- models %>%
  select(Formula, Pred) %>%
  unnest() %>%
  select(`.rownames`, names(mtcars), Formula, `.fitted`) %>%
  spread(Formula, `.fitted`)
Related