【问题标题】:How do I add more model predictions after using gather_predictions()?使用gather_predictions() 后如何添加更多模型预测?
【发布时间】:2019-02-12 22:28:44
【问题描述】:

我使用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)

【问题讨论】:

    标签: r dplyr modelr


    【解决方案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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 2018-09-30
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多