Search code examples
rloopsregressionlagdummy-data

R Forecast with lagged dependent variable


Use lm function in to fit (Pt=aPt-1 + bXt + Dummy variable for each quarter) to fit the sample data. How to create n.ahead=12 forecast? Couldnt figure out how to set up dummy and Pt-1 fore iteration.Any help is appreciated!


Solution

  • Maybe this can help

    #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] }
    
    }