rpurrrlme4sjplot

Plot multiple interaction plots using sJplot::plot_model for multiple outcomes


I want to generate multiple interaction plots from multiple outcomes data using sjPlot::plot_model.

For example, I am using a dataset MathAchive from nlme and load these packages

library(nlme)
library(lme4)
library(sjPlot)
library(broom.mixed)

My objectives are:

The results that I want should look like below but I want to apply DRY principle and would prefer using purrr::map

mod_math <- 
  lmer(MathAch ~ Minority*Sex + (1| School), 
             data = MathAchieve) 
plot_model(mod_math, type = "int")

mod_ses <- 
  lmer(SES ~ Minority*Sex + (1| School), 
       data = MathAchieve) 
plot_model(mod_ses, type = "int")

I could get multiple tidy results using purrr::map

MathAchieve |> 
  select(MathAch, SES) |>
  map(~ lmer(.x ~ Minority*Sex + (1| School), 
             data = MathAchieve)) |>
  map(~tidy(.x))

But I receive errors when using purrr::map like below

MathAchieve |> 
  select(MathAch, SES) |>
  map(~ lmer(.x ~ Minority*Sex + (1| School), 
             data = MathAchieve)) |>
  map(~ plot_model(.x, type = "int"))

MathAchieve |> 
  select(MathAch, SES) |>
  map(~ lmer(.x ~ Minority*Sex + (1| School), 
             data = MathAchieve) |>
        plot_model(., type = "int"))

What should I do to get multiple interaction plots from models with multiple outcomes?


Solution

  • One option to fix your issue would be to apply map on a vector of the outcome variable names and use reformulate to create the formula:

    library(nlme)
    library(lme4)
    library(sjPlot)
    library(broom.mixed)
    library(purrr)
    
    c("MathAch", "SES") |>
      map(~ lmer(
        reformulate("Minority * Sex + (1 | School)", .x),
        data = MathAchieve
      )) |>
      map(~ plot_model(.x, type = "int")) |> 
      set_names(c("MathAch", "SES"))
    #> $MathAch
    

    #> 
    #> $SES