Home > Back-end >  How can I use a for loop to run regression in r?
How can I use a for loop to run regression in r?

Time:03-29

My current dataset looks like:

wage <- rnorm(10000)

educ <- rnorm(10000)

age <- rnorm(10000)

tce<- rnorm(10000)

work <- rbinom(n=10000,size=1,prob=0.05)

manu <- rbinom(n=10000,size=1,prob=0.05)

id <- rnorm(10000)

df <- data.frame(wage, educ, age, tce, work, manu, id)

wage, work and manu are my dependent variables, and the rest of my variables are my independent variables.

Currently, I am repeating the syntax, but just changing the outcome variable as such:

library(fixest)

model1 <- feols(work ~ educ   age   tce | id, data = df)

model2 <- feols(manu ~ educ   age   tce | id, data = df)

model2 <- feols(wage~ educ   age   tce | id, data = df)

Is there a way I can use a for loop to run such regressions?

Moreover, after running the regressions, I would also like to plot the coefficients of the regressions as such:

library(modelsummary)

modelplot(
 list(model1, model2, model3)
 )

However, since for-loops don't create new objects how can I plot the coefficients?

Thank you.

CodePudding user response:

I can't replicate your example with the provided code. Neverthless, you can use a loop like this:

variable <- c("work", "manu", "wage")
datalist <- list()

for(i in variable) {
  formula <- as.formula(paste(i, " ~ educ   age   tce | id"))
  model <- feols(formula, data = df)
  datalist[[i]] <- model
}

The model for each condition will be saved in a list that you can access or extract as an object.

  • Related