我正在尝试制作一个预测模型,其中我每年执行多个汇总回归(基于前几年),因此允许系数随时间变化。 (这在提供的样本数据中可能没有意义,但在实践中我的样本已经完成了。)
以下是我到目前为止的情况:我将代码调整为plm包中的可重现样本:
数据采用以下方式(面板)构建,公司年份已编入索引。
> head(Grunfeld)
firm year inv value capital
1 1 1935 317.6 3078.5 2.8
2 1 1936 391.8 4661.7 52.6
3 1 1937 410.6 5387.1 156.9
4 1 1938 257.7 2792.2 209.2
5 1 1939 330.8 4313.2 203.4
6 1 1940 461.2 4643.9 207.2
这是我的代码:
library(plm)
data("Grunfeld", package="plm")
# Store each subset regression in myregression
myregression <- list()
count <- 1
## pooled regression in each year t,
## with subset data of the previous six years (t-5)
for(t in 1940:1950){
myregression[[count]] <- plm(inv ~ value + capital,
subset(Grunfeld, year<=t & year>=t-5),
index=c("firm","year"))
# Name each regression based on the year range included in the data subset
names(myregression)[[count]] = paste0("Year_",t)
count <- count+1
}
## Prediction
#######################
# Alternative 1: Loop
Forecast<-list()
count<-1
for(t in 1940:1950){
Forecast[[count]]<-predict(myregression[[count]], subset(Grunfeld, year==t))
## Name each Prediction based on the year t:
names(Forecast)[[count]] = paste0("Year_",t)
count <- count+1
}
不幸的是我的代码不起作用,我收到以下错误:
Error in crossprod(beta, t(X)) : non-conformable arguments
理想情况下,我希望将我的预测/预测存储在$ Grunfeld $ Forecast中,其结构与原始Grunfeld数据相同。但是,我在使用列表时遇到了很多困难,并且经常无法正确解决它们并将结果存储在原始数据旁边的向量中。这是至关重要的,因为在我自己的样本中,存在大量缺失数据(NA),并且我只能在有限子集上使用预测函数。你如何以理想的方式安排数据?
这是获得条件预测(年度)的正确方法,这些预测具有不同的斜率,并以与原始数据相同的方式存储它们,还是有更有效的方式我不知道?
答案 0 :(得分:1)
请注意,您没有估算合并回归。默认情况下,plm
会估算within
模型。第一次回归的快速摘要揭示了这一点。参见例如summary(myregression[[1]]
,其第一行如下:
Oneway (individual) effect Within Model
Call:
plm(formula = inv ~ value + capital, data = subset(Grunfeld,
year <= t & year >= t - 5), index = c("firm", "year"))
...
由于您谈到了池化回归,请尝试以下代码。我冒昧地把它缩短了一点:
for(t in 1940:1950){
myregression[[as.character(t)]] <- plm(inv ~ value + capital,
subset(Grunfeld, year<=t & year>=t-5),
index=c("firm","year") , model="pooling")
}
for(t in 1940:1950){
Forecast[[as.character(t)]]<-predict(myregression[[as.character(t)]],
subset(Grunfeld, year==t))
}
这为您提供了没有错误消息的预测值。
我无法评论您关于这是否是正确的统计方法的最后一个问题,但我希望R相关问题得到解决。
要回复您的评论,请尝试
Grunfeld$forc <- NA
for(t in 1940:1950){
Grunfeld[which(Grunfeld$year==as.character(t)), "forc"] <-
predict(myregression[[as.character(t)]], subset(Grunfeld, year==t))
}