具有滞后因变量的 R 预测

R Forecast with lagged dependent variable

使用lm function in to fit (Pt=aPt-1 + bXt + 每个季度的虚拟变量)来拟合样本数据。如何创建 n.ahead=12 预测?在 iteration.Any 帮助之前无法弄清楚如何设置虚拟和 Pt-1!

也许这可以帮助

#store your model
model<-your_model

#get the last pt observation
last<-dato[nrows(dato$pt), c('pt', 'age')]

years<-12/4

#create dummy
t1<-rep(c(1,0,0,0) , years)
t2<-rep(c(0,1,0,0) , years)
t3<-rep(c(0,0,1,0) , years)
t4<-rep(c(0,0,0,1) , years)

#create pt observation
pt<-c(last$pt, rep(NA, length(t1)-1 ))

df<-data.frame(t1=t1,t2=t2,t3=t3,t4=t4,lag_pt=pt, age=last$age)

df$predict<-NA

for (i in 1:nrow(df) )
{
df$predict[i]<-predict(model, data=df[i,])

if (i!=nrow(df))
{df$lag_pt[i+1]<-df$predict[i] }

}