Benja Ramone
Benja Ramone

Reputation: 7

Extract beta from multiple linear regressions with R

I have 34 regressions, the same one for different municipalities, done with the function lm() and I would like to make a table the name of the municipality and the third beta of each regression I created the regressions with this loop

for ( i in 1:34 ){
  #create a subset data 
  data_sub <- subset(dif_dif, Comuna_subida == comunas[i])
  
  assign(paste("lm", comunas[i] , sep = "_"), lm(log(viajes) ~ 
                            # Explanatory variables
                            cierre_colegio + Cuarentena.x + 
                            dias_en_cuarentena +
                            # Control variables
                            n_comunas_cuarentena +
                            personas_en_cuarentena +
                            # Time Variables
                            dia_semana_Tuesday + dia_semana_Wednesday +
                            dia_semana_Thursday + dia_semana_Friday +
                            mes_4 + mes_5 + mes_6 + mes_7 + semana +
                            semana_corta + ano,
                          data = data_sub))
}

comunas is a list with the names of all the municipalities.

So, now I have 34 regressions called lm_X and I would like to have a table like this:

Municipality     beta_Cuarentena.x 
X1                0.08
X2                0.15
X3                0.42
...etc

Thanks very much!

Upvotes: 1

Views: 738

Answers (2)

Waldi
Waldi

Reputation: 41210

Instead of assigning the results to variables with different names, you could create a list.
As an example :

library(purrr)
library(dplyr)

# Calculate regressions
lmcalc <- list()

for (i in 1:3) {
  x <- 1:20
  y <- 2 * x+rnorm(20)
  lmcalc[[paste("Municipality",LETTERS[i])]] <- lm(y~x)
}

lmcalc %>% imap(~{data.frame( beta = setNames(.x$coefficients[2],.y))}) %>%
           bind_rows 
#>                    beta
#> Municipality A 2.023770
#> Municipality B 1.981352
#> Municipality C 2.015938

Created on 2020-09-22 by the reprex package (v0.3.0)

The imap function allows to loop over the list with .x representing the current object in the list and .y its name.

Upvotes: 1

cbowers
cbowers

Reputation: 167

Initialize a data.frame outside of your for loop with two columns. Let's call it df. Then within the for loop, add a line of code that creates a new row for every lm model. It should look something like: df[i,] <- c(comunas[i], get(paste("lm", comunas[i] , sep = "_"))$coefficients[3])

Upvotes: 0

Related Questions