lundi 26 août 2019

How to run a for loop to run regressions by dummy variables

I have the following code:

library(Jmisc)
library(tidyverse)
library(lmtest)
library(plm)
library(multiwayvcov)

reg <- lm(Y ~ x1 + x1_sq + x2 + x2_sq + x1x2 + d2 + d3 + d4, df)

Where all x_i are continuous variables and d_i are mutually exclusive dummy variables (d1 is present but exclude to avoid perfect multicollinearity). Rather than including the dummy variables, I want to run separate regressions for each dummy variable == 1. I wish to achieve this through a loop in the following form:

dummylist <- list("d1", "d2", "d3", "d4")
for(i in dummylist){
   if(i==1){
      ireg <- lm(Y ~ x1 + x1_sq + x2 + x2_sq + x1x2, df)
   } else {
      Unsure what to put here
   }
}

My three(?) questions are: in the first section of the -if- function, do I just include "i" before "reg" for my code to generate results "d1reg, d2reg, etc."? and, included in the code above, what would I put after the -else- statement? This all begs the question, is putting an if-else statement within the -for- loop the wrong approach/is there a more appropriate loop?

Sorry if this is too much, please let me know if it is and I can cut it down or separate into multiple questions. I could not find a similar question, probably as I am rather new to running loops in R and don't know what to look for.

Aucun commentaire:

Enregistrer un commentaire