保存并访问循环中的回归结果

时间:2014-01-22 13:37:20

标签: r for-loop lapply

我正在尝试通过pml中的for loop包进行多个面板数据回归,然后保存结果,以便我可以在每个回归结果上使用summary。但是,我似乎无法弄清楚如何在已保存结果的summary上使用list。这就是我的尝试:

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))

然而,我收到错误:

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

我可能不会以非常明智的方式保存回归结果,并且可能可以避免使用for loop,我只是不知道如何。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:3)

将plm对象存储在列表中。因此,在循环之前创建一个空对象(out),然后在循环中填充它。

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)

此处我还做了其他更改:

  • 循环1,2,3,...而不是2001,2002
  • 不想覆盖DataTests - &gt;已重命名为take