3
votes

I'm trying to: (1) estimate multiple models where only the dependent variable changes (2) Tabulate the results with the Stargazer package

The following code works, but I have to repeat a line of code for each model:

    library(stargazer)
    data(mtcars)

    reg1 <- lm(mpg ~ am + gear + carb, data=mtcars)
    reg2 <- lm(cyl ~ am + gear + carb, data=mtcars)
    reg3 <- lm(disp ~ am + gear + carb, data=mtcars)

    stargazer(reg1, reg2, reg3,
              title="Regression Results", type="text", 
              df=FALSE, digits=3)

You can see that the (trimmed) output has the correct headings for the dependent variables (mpg, cyl, disp):

Regression Results
==================================================
                         Dependent variable:      
                    ------------------------------
                       mpg       cyl       disp   
                       (1)       (2)       (3)    
--------------------------------------------------
am                   3.545*    -0.176    -40.223  
                     (1.897)   (0.615)   (48.081) 

If I use lapply and paste, it ends up changing the headings of the dependent variables in stargazer:

dependents <- c('mpg', 'cyl', 'disp')
outs <- lapply(dependents, function(x) {
  fit <- lm(paste(x,'~', 'am + gear + carb'), data=mtcars)})

stargazer(outs[[1]], outs[[2]], outs[[3]],
          title="Regression Results", type="text", 
          df=FALSE, digits=3)

gives the output where x is the heading for the dependent variables:

Regression Results
==================================================
                         Dependent variable:      
                    ------------------------------
                                  x               
                       (1)       (2)       (3)    
--------------------------------------------------
am                   3.545*    -0.176    -40.223  
                     (1.897)   (0.615)   (48.081) 

Is there any way for me to fix this? Thank you.

1

1 Answers

5
votes

If you create the formula before you run the regression it should work. I just separated the formula creation and the regression.

dependents <- c('mpg', 'cyl', 'disp')
outs <- lapply(dependents, function(x) {
  formula <- as.formula(paste(x,'~', 'am + gear + carb'))
  fit <- lm(formula, data=mtcars)})

stargazer(outs[[1]], outs[[2]], outs[[3]],
      title="Regression Results", type="text", 
      df=FALSE, digits=3)