使用collect_predictions()后如何添加更多模型预测?

时间:2019-02-12 22:28:45

标签: r dplyr modelr

我使用collect_predictions()向我的数据帧添加了几个预测。稍后,也许在进行了一些可视化之后,我想添加新模型的预测。我似乎不知道该怎么做。

我尝试使用add_predictions()和collect_predictions(),但是当我只想添加其他行时,它们添加了全新的列。

library(tidyverse)
library(modelr)

#The 3 original models
mdisp = lm(mpg ~ disp, mtcars) 
mcyl = lm(mpg ~ cyl, mtcars)
mhp = lm(mpg ~ hp, mtcars)

#I added them to the data frame.
mtcars_pred <- mtcars %>%
  gather_predictions(mdisp, mcyl, mhp)

#New model I want to add.
m_all <- lm(mpg ~ hp + cyl + disp, mtcars)

1 个答案:

答案 0 :(得分:1)

似乎有两个选择。

1:重组代码,以便在末尾使用gather_predictions()

library(tidyverse)
library(modelr)

#The 3 original models
   mdisp <- lm(mpg ~ disp, mtcars) 
   mcyl <- lm(mpg ~ cyl, mtcars)
   mhp <- lm(mpg ~ hp, mtcars)

# New model
   m_all <- lm(mpg ~ hp + cyl + disp, mtcars)

# Gather predictions for all four models at the same time
   mtcars_pred <- mtcars %>%
     gather_predictions(mdisp, mcyl, mhp, m_all)

2:使用bind_rows()加上另一个对gather_predictions()的呼叫

library(tidyverse)
library(modelr)

#The 3 original models
  mdisp <- lm(mpg ~ disp, mtcars) 
  mcyl <- lm(mpg ~ cyl, mtcars)
  mhp <- lm(mpg ~ hp, mtcars)

# Get predictions from the first three models
  mtcars_pred <- mtcars %>%
    gather_predictions(mdisp, mcyl, mhp)

# New model
  m_all <- lm(mpg ~ hp + cyl + disp, mtcars)

# Get the new model's predictions and append them
  mtcars_pred <- bind_rows(mtcars_pred,
                           gather_predictions(data = mtcars,
                                              m_all))