I have a series of linear models that I've run and I want to be able to output the residuals from specific years and match those residuals to the companies.

The data looks similar to that shown below

Year    Company         pctEarn
1990    3M Company      0.295918367
1991    AT&T            0.251497006
1992    Ford            0.293233083
1993    Microsoft       0.264705882

The loop to run through the LMs looks like below

fits <- list()

for(i in 2000:2012){
  dtSub <- subset(dt, Year <= i)
  fit <- lm(pctEarn ~ Year + Company, data = dtSub)
  fits[[i - 1999]] <- fit
}

What I'm having issues with is retrieving the residuals for specific companies from the output.

Ideally I'd be able to create an output for each regression that looks like below

Year Company    pctEarn    Predicted  Residual
1990 3M Company 0.2959     0.4523     0.16000
Etc......

Any hints would be appreciated.

有帮助吗?

解决方案

So what I figured out which isn't ideal for large regressions is to simply build up a data frame that accumulates regression results and I can cut it up later.

out <- data.frame()
for(i in 2000:2012){
  dtSub <- subset(dt, Year <= i)
  fit <- lm(pctEarn ~ y2 + Company, data = dtSub)
  fits[[i - 1999]] <- fit
  dtSub$fitted <- fitted(fit)
  dtSub$resid <- residuals(fit)
  dtSub$reg <- i
  out <- rbind(out, dtSub)
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top