增强原始数据集中许多模型的预测

Augment predictions from many models in the original dataset

我想要 运行 许多具有 x 和 ys 的所有可能组合的模型。我创建了以下代码来执行此操作。

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)))

现在,我想从原始数据集中的所有这些模型中获取所有预测,这里是 mtcars。我怎样才能做到这一点?有没有办法使用扫帚增强?

您可以使用 mapaugment,类似于将 glm 适合每一行的方式。

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))

预测位于 Pred 列表中每个数据帧的 .fitted 列。

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