A month ago, I posted this question and I was able to solve it myself; however, after doing an update (easystats::easystats_update()), it no longer works. Therefore, my question remains the same: how can I save the diagnostics plot that is the output of check_model(model) from within a script?
When I do:
diagnost_fig = check_model(model)
ggsave(diagnostic_path, plot = diagnost_fig)
I get the error: Error in UseMethod("grid.draw") : no applicable method for 'grid.draw' applied to an object of class "c('check_model', 'see_check_model')"
Then, when I plot it first:
diagnost_fig = plot(check_model(model))
ggsave(diagnostic_path, plot = diagnost_fig)
I now get the error: Error in UseMethod("grid.draw") : no applicable method for 'grid.draw' applied to an object of class "list"
Is there a way to save the plot as I visualize it in
Here is a script that replicates this problem:
# Close all windows and clear all variables
rm(list = ls())
graphics.off()
# Load libraries
library(lme4)
library(ggplot2)
library(easystats)
library(see)
### Create example dataset
# Define the number of groups, time points, measures, and variables
n_groups = 2
time_points = c(1,5,9,12)
n_subjects = 8
n_variables = 2
# Create all combinations of groups, time points, and measures, and head data
data = expand.grid(group = paste0("Group",1:n_groups), time = time_points, subject = 1:n_subjects)
data = data[order(data$group, data$time, data$subject), ]
for (i in 1:n_variables) {data[[paste0("var", i)]] <- rnorm(nrow(data))}
head(data)
# Loop through variables
for (variable in paste0("var", 1:n_variables)) {
# Create linear mixed model
model = lmer(data[[variable]] ~ time*group + (1 + time | subject), data, control = lmerControl(optimizer ="Nelder_Mead"))
# Create paths to save boxplot and diagnostic plot
boxplot_path = paste0("Example_Boxplot_", variable, ".png")
diagnostic_path = paste0("Example_Diagnostic_", variable, ".png")
# Create boxplot
variable_boxplot = ggplot(data,
aes(x = time,
y = !!sym(variable),
group = interaction(time, group),
fill = group)) +
geom_boxplot(width = 3,
position = position_dodge(width = 1.5),
alpha = 0.6)
# Save boxplot
ggsave(boxplot_path, plot = variable_boxplot)
# PROBLEM: Create and try to save diagnostic plot
# First try:
check_model(model)
# ggsave(diagnostic_path) # Just saves again the boxplot
# Second try (prompts error):
diagnost_fig = check_model(model)
# ggsave(diagnostic_path, plot = diagnost_fig)
# Error in UseMethod("grid.draw") :
# no applicable method for 'grid.draw' applied to an object of class "c('check_model', 'see_check_model')"
# Third try (prompts error):
diagnost_fig = plot(check_model(model))
# ggsave(diagnostic_path, plot = diagnost_fig)
# Error in UseMethod("grid.draw") :
# no applicable method for 'grid.draw' applied to an object of class "list"
}