1

我使用gather_predictions() 将几个预测添加到我的数据框中。稍后,也许在做了一些可视化之后,我想添加一个新模型的预测。我似乎无法弄清楚如何做到这一点。

我尝试使用 add_predictions() 和 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)

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

1 回答 1

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()plus 另一个调用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))
于 2019-02-12T22:46:17.583 回答