I am running a series of glms using the below code, run in R Markdown. I need the AIC table to include the variable names (not just the name of the model).
# Specify the names of predictor variables
predictor_vars <- c("communitiesinpa", "formalprotection", "attitudewildlife", "competitionlivestock", "fenced", "parkresourcescat", "routinepatrols", "mitigationlivestockbarriers", "mitigationcommunityengagement")
# Create all possible combinations of predictor variables
all_combinations <- unlist(lapply(1:length(predictor_vars), function(x) combn(predictor_vars, x, simplify = FALSE)), recursive = FALSE)
# Create an empty list to store the GLM models
models_list <- list()
# Fit GLMs for all combinations and store them in the models_list
for (i in seq_along(all_combinations)) {
formula_string <- paste("totalthreatscore ~", paste(all_combinations[[i]], collapse = "+"))
formula_object <- as.formula(formula_string)
model <- glm(formula_object, data = glmdata, family = Gamma)
models_list[[i]] <- model
}
# Print the summary of each model
for (i in seq_along(models_list)) {
cat("Model with predictors:", paste(all_combinations[[i]], collapse = " + "), "\n")
print(summary(models_list[[i]]))
cat("\n")
}
AIC_table <- aictab(models_list)
# Display the AIC table
knitr::kable(AIC_table)
aictab
provides the model numbers (i.e., 1 to >500), but does not include the variable names. Can anyone assist with modifying the code to include these?
You could add the variables as
attr
ibute to each model. Demonstrated onmtcars
with slightly simplified code.(This answer elaborates on the use of
do.call
here.)The use of
bbmle::AICctab
was recommended1. We can produce character strings out of the p.vars usingtoString()
andcbind
.