Home > Software engineering >  Elegant coding format when applying the same analysis for several models
Elegant coding format when applying the same analysis for several models

Time:11-15

Absolute beginner here. So, I have run the following models, employed robust se and, using stargazer(), I have obtained a nice table format. However, as you can probably see, there are lots of repetitions and the code is quite long. I would like to ask you whether there exists a way to write this code in a more elegant and succinct manner, as I might add further models.

Thank you for any suggestions!

pooled1 <- plm(model1, data=combined, model="pooling", index=c("iso3n.x", "year.x"))
pooled1_robust <- coeftest(pooled1,vcov=vcovHC(pooled1,method = "arellano", type="HC3"))

pooled2 <- plm(model2, data=combined, model="pooling", index=c("iso3n.x", "year.x"))
pooled2_robust <- coeftest(pooled2,vcov=vcovHC(pooled2,method = "arellano", type="HC3"))

pooled3 <- plm(model3, data=combined, model="pooling", index=c("iso3n.x", "year.x"))
pooled3_robust <- coeftest(pooled3,vcov=vcovHC(pooled3, method = "arellano", type="HC3"))

stargazer(pooled1_robust, type="text")
stargazer(pooled2_robust, type="text")
stargazer(pooled3_robust, type="text")

CodePudding user response:

The standard way of solving this type of repetitive code is to put the data, in this case model*, in a list and then lapply a function to the list members.

models_list <- list(model1, model2, model3)

pooled_list <- lapply(models_list, function(x){
  plm(x, data=combined, model="pooling", index=c("iso3n.x", "year.x"))
})

robust_list <- lapply(pooled_list, function(x){
  coeftest(x, vcov = vcovHC(x, method = "arellano", type = "HC3"))
})
  • Related