0

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?

1 Answer 1

1

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) 
   }    
}

or with shorter code:

for (i in seq_along(depvars)) {
    for (j in seq_along(indepvars)) {
       assign(paste0(depvars[i], "_", indepvars[j]), lm(as.formula(paste(depvars[i], "~", paste(c(indepvars[j], confounders), collapse = "+"))), data = mtcars)) 
   }    
}```
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works. May I ask you why your code also creates a "my_model" object which is identical to one of the stored results (in this case, "wt_carb")?
It’s just a temporary object to keep the code more readable. I didn’t bother removing it. You can also use one line within the loops to avoid this: assign(paste0(depvars[i], "_", indepvars[j]), lm(as.formula(paste(depvars[i], "~", paste(c(indepvars[j], confounders), collapse = "+"))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.