rplotlinear-regressiondiagnostics

r check_model() for model summaries as list objects and 6 plots in 1 row


I'm using the check_model function within the performance library in r to check the assumptions of a simple linear regression model using lm.

I am fitting 3 models on different subsets of the data.

data("mtcars")
head("mtcars")

table(mtcars$cyl, useNA = "ifany")

foo <- mtcars %>%
          group_by(cyl) %>%
             nest() %>%
               mutate(model= map(data, lm(mpg ~ hp + wt, data = .))

foo %>%
    {map(.$model, summary)}

I want check_model to plot all the 6 diagnostic plots per model in one row. Which means 3 rows, 6 plots in each row, using the model summaries which is stored as a list object.

check_model(foo$model..cylinder 4)...all 6 plots in 1 row
check_model(foo$model..cylinder 6)...all 6 plots in 1 row
check_model(foo$model..cylinder 8)...all 6 plots in 1 row

Any suggestions for how to accomplish this is much appreciated. Thanks.


Solution

  • one approach:

    1. create list of models, one model per level of cyl (here: by spliting and Mapping):
    the_models <- 
      split(mtcars, mtcars$cyl) |>
      Map(f = \(d) lm(mpg ~ hp + wt, data = d))
    
    1. map above list into list of plots. The plots produced by plotting the result of check_model have, besides being ggplot-objects, class patchwork, meaning that you can specify the plot_layout (a function provided by package {patchwork}):
    the_plots <- 
      the_models |>
      Map(f = \(m) check_model(m) |>
                   plot() +
                   ## lay out diagnostic plots
                   ## into 6 columns, 1 row per model:
                   plot_layout(6, 1)
          )
    
    1. combine (Reduce) the list of plots into one stack. With {patchwork}, you stack plots with /:
    the_plots |> Reduce(f = `/`)
    

    use {patchwork} to row-bind plots

    edit The output for a larger number of models (= rows) may exceed the device dimensions (Error: The viewport may be too small to show this patchwork. Please make it larger.) If you don't need live preview, you can assign the combined plots to an object and save it like so:

    all_plots <- the_plots |> Reduce(f = `/`)
    ggsave(all_plots, filename = 'all_plots.pdf', height = 20, width = 15)
    

    (ggsave can save in various raster and vector formats, guessing from the filename's extension.)