1

I used gather_predictions() to add several predictions to my data frame. Later on, perhaps after doing some visualizations, I want to add a new model's predictions. I can't seem to figure out how to do this.

I tried using add_predictions() and gather_predictions() but they added entirely new columns when I just want to add additional rows.

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)
bschneidr
  • 6,014
  • 1
  • 37
  • 52
Robin
  • 119
  • 2
  • 8

1 Answers1

1

It seems like there are two options.

1: Restructure your code so that gather_predictions() is used at the end

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: Use bind_rows() plus another call to 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))
bschneidr
  • 6,014
  • 1
  • 37
  • 52