I need to estimate a number of linear models on the same dataset, and put the regression results all into one table. For a reproducible example, here's a simplification using mtcars
:
formula_1 = "mpg ~ disp"
formula_2 = "mpg ~ log(disp)"
formula_3 = "mpg ~ disp + hp"
Currently, my approach has been to:
- Create a list that contains all of the formulae.
- use
purrr:map()
to estimate all of thelm
models. - use
stargazer::
to produce output tables.
library(tidyverse)
library(stargazer)
formula_1 = "mpg ~ disp"
formula_2 = "mpg ~ log(disp)"
formula_3 = "mpg ~ disp + hp"
lst <- list(formula_1, formula_2, formula_3)
models<- lst %>% map(~lm(., mtcars))
stargazer(models, type = "text")
Which gives me the output I'm looking for:
#>
#> =========================================================================================
#> Dependent variable:
#> ---------------------------------------------------------------------
#> mpg
#> (1) (2) (3)
#> -----------------------------------------------------------------------------------------
#> disp -0.041*** -0.030***
#> (0.005) (0.007)
#>
#> log(disp) -9.293***
#> (0.787)
#>
#> hp -0.025*
#> (0.013)
#>
#> Constant 29.600*** 69.205*** 30.736***
#> (1.230) (4.185) (1.332)
#>
#> -----------------------------------------------------------------------------------------
#> Observations 32 32 32
#> R2 0.718 0.823 0.748
#> Adjusted R2 0.709 0.817 0.731
#> Residual Std. Error 3.251 (df = 30) 2.579 (df = 30) 3.127 (df = 29)
#> F Statistic 76.513*** (df = 1; 30) 139.350*** (df = 1; 30) 43.095*** (df = 2; 29)
#> =========================================================================================
#> Note: *p<0.1; **p<0.05; ***p<0.01
First Question:
How can I put all of the formulae into a list when there are many formula? The line below works if there are only 3 formulae, but seems clumsy when there are many models to be estimated.
lst <- list(formula_1, formula_2, formula_3)
Follow up Question:
Is there a better way to accomplish the entire task, using say broom
or another method? Or is purrr:map()
a reasonable solution?
mutate(models = map(forumulas, ...)
. As far as generating all the formulas you could do some fancy work by building a function that takes your IV, DVs, and some modifying function and then pastes together a formula. – Luganda