将滚动回归生成的所有数据编译成一个

时间:2013-10-14 12:37:25

标签: r compilation regression rolling-computation

我正在使用庞大的数据库进行滚动回归,并且用于滚动的参考列称为" Q"每个数据块的值为5到45。起初我一步一步地尝试使用简单的代码,它的效果非常好:

fit <- as.formula(EB~EB1+EB2+EB3+EB4)
#use the 20 Quarters data to do regression
model<-lm(fit,data=datapool[(which(datapool$Q>=5&datapool$Q<=24)),])
#use the model to forecast the value of next quarter
pre<-predict(model,newdata=datapool[which(datapool$Q==25),])
#get the forecast error
error<-datapool[which(datapool$Q==25),]$EB -pre

上面代码的结果是:

> head(t(t(error)))
        [,1]
21   0.006202145
62  -0.003005097
103 -0.019273856
144 -0.016053012
185 -0.025608022
226 -0.004548264

数据池具有以下结构:

> head(datapool)
  X  Q            Firm         EB       EB1        EB2        EB3
1 1  5 CMCSA US Equity 0.02118966 0.08608825 0.01688180 0.01826571
2 2  6 CMCSA US Equity 0.02331379 0.10506550 0.02118966 0.01688180
3 3  7 CMCSA US Equity 0.01844747 0.12961955 0.02331379 0.02118966
4 4  8 CMCSA US Equity         NA         NA 0.01844747 0.02331379
5 5  9 CMCSA US Equity 0.01262287 0.05622834         NA 0.01844747
6 6 10 CMCSA US Equity 0.01495291 0.06059339 0.01262287         NA
       ...
       Firm B(also from Q5 to Q45)
       ...
       Firm C(also from Q5 to Q45)

上面产生的错误都标有&#34; X&#34; &#34;数据池&#34;中的值,所以我可以知道错误来自哪家公司。

因为我需要运行21次回归(5-24,6-25,...,25-44之间),所以我不想这么做,并且想出了以下代码:

fit <- as.formula(EB~EB1+EB2+EB3+EB4)
for (i in 0:20){
model<-lm(fit,data=datapool[(which(datapool$Q>=5+i&datapool$Q<=24+i)),])
pre<-predict(model,newdata=datapool[which(datapool$Q==25+i),])
error<-datapool[which(datapool$Q==25),]$EB -pre
}

上面的代码有效,没有出现错误,但我不知道如何自动将每个回归产生的所有错误编译成一个数据池?任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

(我再说一遍:对于一个向量使用名称&#39;错误&#39;真是个坏主意。)它是核心功能的名称。这就是我尝试这项任务的方式。 (使用子集参数和索引比折磨哪些语句。

fit <- as.formula(EB~EB1+EB2+EB3+EB4)
pre <- numeric(len=21)
errset <- numeric(len=21)
for (i in 0:20){
     model<-lm(fit,data=datapool, subset= Q>=5+i & Q<=24+i )
     pre[i]<-predict(model,newdata=datapool[ datapool[["Q"]] %in% i:(25+i), ])
     errset[i]<-datapool[25+i,]$EB -pre
}
errset

由于您没有提供数据或数据对象的全面描述,因此在开始或结束时运行tof数据不会导致错误。