循环保存和访问回归结果 [英] Saving and accessing results from regression in a loop
问题描述
我试图通过for loop
中的pml
包进行几次面板数据回归,然后保存结果,以便可以对每个回归结果使用summary
.但是,我似乎无法弄清楚如何在保存结果的list
上使用summary
.这是我尝试过的:
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))
但是,我得到了错误:
Error in tapply(x, effect, func, ...): Arguments must have same length
我可能不会以非常明智的方式保存回归结果,并且可能会避免for loop
,我只是不知道怎么做.任何帮助表示赞赏!
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!
推荐答案
将plm对象存储在列表中.因此,请在循环之前创建一个空对象(out
),然后将其填充到循环中.
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:
- 循环1,2,3,...,而不是2001、2002
- 不想覆盖DataTests->重命名为
take
这篇关于循环保存和访问回归结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!