Home > Blockchain >  R code for looping through regression models, starting from Stata code
R code for looping through regression models, starting from Stata code

Time:01-27

New R user here, coming from Stata. Most of my work consists of running several regression models with different combinations of dependent and independent variables and storing the results. For this, I make extensive use of macros and loops, which to my understanding are not preferred in R.

Using the "mtcars" dataset as an example, and assuming I'm interested in using mpg, disp and wt as dependent variables, hp and carb as independent variables and adjusting all models for vs, am and gear, in Stata I would do something like this:

local depvars mpg disp wt // create list of dependent variables
local indepvars hp carb // create list of independent variables
local confounders vs am gear // create list of control variables

foreach depvar of local depvars {
    foreach indepvar of local indepvars {
        reg `depvar' `indepvar' `confounders'
        estimates store `depvar'_`indepvar'
    }
}

Is there a way to do it in R? Potentially using the tidyverse approach which I'm starting to get familiar with?

CodePudding user response:

This will make R to follow your Stata code:

depvars <- c('mpg', 'disp', 'wt')
indepvars <- c('hp', 'carb') 
confounders <- c('vs', 'am', 'gear')

for (i in seq(length(depvars))) {
    for (j in seq(length(indepvars))) {
       my_model <- lm(as.formula(paste(depvars[i], "~", paste(c(indepvars[j], confounders), collapse = " "))), data = mtcars)
       assign(paste0(depvars[i], "_", indepvars[j]), my_model) 
   }    
}
  • Related