I am trying to get a sliding dynamic time series prediction in R (and then work out the square prediction errors). I have a lot of this code based on https://stackoverflow.com/a/1386948/ ... , but I'm very new to R, so I'm struggling a bit. Any help is appreciated.
require(zoo) require(dynlm) set.seed(12345) #create variables x<-rnorm(mean=3,sd=2,100) y<-rep(NA,100) y[1]<-x[1] for(i in 2:100) y[i]=1+x[i-1]+0.5*y[i-1]+rnorm(1,0,0.5) int<-1:100 dummydata<-data.frame(int=int,x=x,y=y) zoodata<-as.zoo(dummydata) prediction<-function(series) { mod<-dynlm(formula = y ~ L(y) + L(x), data = series) #get model nextOb<-nrow(series)+1 #make forecast predicted<-coef(mod)[1]+coef(mod)[2]*zoodata$y[nextOb-1]+coef(mod)[3]*zoodata$x[nextOb-1] #strip timeseries information attributes(predicted)<-NULL return(predicted) } rolling<-rollapply(zoodata,width=40,FUN=prediction,by.column=FALSE)
This returns:
20 21 ..... 80 10.18676 10.18676 10.18676
I have two problems that I did not expect:
- Works from 20-> 80, not 40-> 100, as you would expect (since the width is 40)
- The forecasts that he issues are constant: 10.18676
What am I doing wrong? And is there an easier way to make a prediction than to write all this? Thanks!
source share