oftentimes I need to fit several linear models (dozens) in R. These models may have the same predictor but varying response variables, data distribution families, and more.
What I've been doing: fitting models one by one, looking at diagnostic plots one by one, and altering the model as needed (see below).
My goal: fit models with functions that fit initial models using a specified set of predictors and response variables and families and datasets. Put those models into one place, like a dataframe, where I can access the model object itself as well as characteristics like the model's AIC or formula. Provide diagnostic plots with DHARMa. If necessary, modify the model and then update the dataframe to reflect that model's changes.
How can I achieve this ideal workflow? I've tried to make a reprex, below. Thanks for any advice!
library(tidyverse)
library(DHARMa)
library(magrittr)
library(glmmTMB)
cars <- datasets::mtcars
# 3 models, each with different response variables. Some (e.g. glm2)
# have non-Gaussian families; some have filtered datasets
lm1 <- glmmTMB(mpg ~ hp, data = cars)
glm2 <- glmmTMB(cyl ~ hp,
data = cars,
family = "poisson")
lm3 <- glmmTMB(drat ~ hp,
data = cars %>%
dplyr::filter(carb != 1))
# next, look at diagnostic plots
plot(DHARMa::simulateResiduals(lm1))
plot(DHARMa::simulateResiduals(glm2))
plot(DHARMa::simulateResiduals(lm3))
# transform one model's response variable to satisfy assumptions
glm2 <- glmmTMB(cyl^2 ~ hp,
data = cars,
family = "poisson")
# check diagnostics again
plot(DHARMa::simulateResiduals(lm2))
# organize models into one place. A dataframe? A list? Somewhere where
# I can access the model itself and the model formula so I can extract
# those things to be used as arguments in other functions
?