Saving and accessing results from regression in a loop

佐手、 提交于 2019-12-08 05:28:49

问题


I am trying to do several panel data regression through the pml package in a for loop and then save the results, so that I can use summary on each of the regression results. However, I can't seem to figure out how to use summary on the list of saved results. This is what I have tried:

library(plm)

########### Some toy data #################

Id <- c(rep(1:4,3),rep(5,2))
Id <- Id[order(Id)]
Year <- c(rep(2000:2002,4),c(2000,2002))

z1 <- rnorm(14)
z2 <- rnorm(14)
z3 <- rnorm(14)
z4 <- rnorm(14)

CORR <- rbind(c(1,0.6,0.5,0.2),c(0.6,1,0.7,0.3),c(0.5,0.7,1,0.4),c(0.2,0.3,0.4,1))
CholCORR <- chol(CORR)
DataTest <- as.data.frame(cbind(z1,z2,z3,z4)%*%CholCORR)
names(DataTest)<-c("y","x1","x2","x3")
DataTest <- cbind(Id, Year, DataTest)

############################################

for(i in 2001:2002){

  Data <- DataTest[(DataTest$Year <= i), ]
  TarLV <- plm(diff(y) ~ lag(x1) + x2 + x3, data = Data, model="pooling", index = c("Id","Year"))
  if(i==2001){
    Res1St <- TarLV
  } else {
    Res1St <- c(Res1St,TarLV)
  }
}

sapply(Res1St, function(x) summary(x))

However, I get error:

Error in tapply(x, effect, func, ...): Arguments must have same length

I probably don't save the regressions results in a very sensible way, and the for loop can probably be avoided, I just don't see how. Any help appreciated!


回答1:


Store the plm object in a list. Therefore create an empty object (out) before the loop and then fill it within the loop.

out <- NULL
yr <- 2001:2002
for(i in seq_along(yr)){
  take <- DataTest[(DataTest$Year <= yr[i]), ]
  out[[i]] <- plm(diff(y) ~ lag(x1) + x2 + x3, data = take, model="pooling", index = c("Id","Year"))

}

lapply(out, summary)

Here I made also other changes:

  • loop over 1,2, 3, ... , instead of 2001, 2002
  • Don't want to overwrite DataTests -> renamed to take


来源:https://stackoverflow.com/questions/21284453/saving-and-accessing-results-from-regression-in-a-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!