user19562955
user19562955

Reputation: 293

How can I run regression for each year?

My code:

for (x in dataset$year){
  controls_c <- paste(controls, collapse = "+")
  spec <- formula(paste(dataset$Inflation,
                        "~MonetaryPolicyShockRomer&Romer+",
                        controls_c, collapse=" "))
  regs_controls[[x]] <- lm(spec, data = dataset %>% filter(x))
}

But I am not sure if filtering would work that way. Sometimes I get error related to filter and sometimes I get the following error: Error in str2lang(x) : :1:65: unexpected numeric constant 1: 3.93652 ~MonetaryPolicyShockRomer&Romer+ Unemployment+OutputGap 4.64304

Upvotes: 0

Views: 150

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76460

Any of the following will run the regressions by groups of year. Untested, since there are no data.

spec <- reformulate(
  termlabels = c("MonetaryPolicyShockRomer&Romer", controls_c),
  reponse = "Inflation"
)

regs_controls <- by(dataset, dataset$year, \(X) lm(spec, data = X))

sp <- split(dataset, dataset$year)
regs_controls2 <- lapply(sp, \(X) lm(spec, data = X))

Upvotes: 1

Related Questions