0

I am running multiple linear regression models and I would like to loop through the results to subsequently generate robust standard errors. My code currently looks like this, but I want to run multiple models and not have to copy the code for calculating robust standard errors for each model.

# load data
data(mtcars)

# run models
m1 <- lm("mpg ~ wt", data = mtcars)
m2 <- lm("mpg ~ wt + hp", data = mtcars)

# calculate robust standard errors
cov1 <- vcovHC(m1, type = "HC3")
robust_se1 <- sqrt(diag(cov1))
cov2 <- vcovHC(m2, type = "HC3")
robust_se2 <- sqrt(diag(cov2))

How could I write a function to handle this task. I plan to number each model using successive integers, e.g., m1, m2, m3. I have not so far been able to adapt related SO answers for generating variables using a loop, like this one.

Edits: changed to executable code.

eric s
  • 197
  • 1
  • 6
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Define `data` so we can run the code. – MrFlick Oct 22 '18 at 19:48
  • See https://stackoverflow.com/questions/42102014/use-lapply-for-multiple-regression-with-formula-changing-not-the-dataset – fishtank Oct 22 '18 at 20:01

0 Answers0