Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Store several regression models in a list in R

I run several regressions (OLS/IV) on different outcome variables. I like to store all results in one list. With 2 models and 3 outcomes, the final list should have 6 elements, and be ordered like OLS1, IV1, OLS2, IV2, OLS3, IV3. Is there another way/shorter/more direct instead of creating a list of list and converting back to a normal list?

library(ivreg)
data(mtcars)

models <- c("mpg", "disp", "hp")

linear_regressions <- list()
iv_regressions <- list()

for (i in models) {
  formula1 <- paste(i, "~ cyl + qsec + carb + drat")
  formula2 <- paste(i, "~ cyl + qsec + carb | drat | wt")
  
  linear_model <- lm(formula = formula1, data = mtcars)
  iv_model <- ivreg(formula = formula2, data = mtcars)
  
  regression_list <- list(linear = linear_model, iv = iv_model)
  
  all_regressions[[i]] <- regression_list
}

flattened_regressions <- unlist(all_regressions, recursive = FALSE)

library(modelsummary)
modelsummary(flattened_regressions, output = "gt") 

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can directly create a list where each element corresponds to an OLS and an IV regression for each outcome variable :

library(ivreg)
data(mtcars)

models <- c("mpg", "disp", "hp")

regressions <- list()

for (i in models) {
  formula1 <- paste(i, "~ cyl + qsec + carb + drat")
  formula2 <- paste(i, "~ cyl + qsec + carb | drat | wt")
  
  linear_model <- lm(formula = formula1, data = mtcars)
  iv_model <- ivreg(formula = formula2, data = mtcars)
  
  regressions[[paste0(i, ".linear")]] <- linear_model
  regressions[[paste0(i, ".iv")]] <- iv_model
}

library(modelsummary)
modelsummary(regressions, output = "gt")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading