title: Dynamic time-series prediction and rollapply
body: <p>I am trying to get a rolling prediction of a dynamic timeseries in R (and then work out squared errors of the forecast).  I based a lot of this code on <a href="https://stackoverflow.com/q/8488147">this StackOverflow question</a>, but I am very new to R so I am struggling quite a bit.  Any help would be much appreciated.  </p>
  
  <pre class="lang-r prettyprint-override"><code>require(zoo)
  require(dynlm)
  
  set.seed(12345)
  #create variables
  x&lt;-rnorm(mean=3,sd=2,100)
  y&lt;-rep(NA,100)
  y[1]&lt;-x[1]
  for(i in 2:100) y[i]=1+x[i-1]+0.5*y[i-1]+rnorm(1,0,0.5)
  int&lt;-1:100
  dummydata&lt;-data.frame(int=int,x=x,y=y)
  
  zoodata&lt;-as.zoo(dummydata)
  
  prediction&lt;-function(series)
    {
    mod&lt;-dynlm(formula = y ~ L(y) + L(x), data = series) #get model
     nextOb&lt;-nrow(series)+1
     #make forecast
     predicted&lt;-coef(mod)[1]+coef(mod)[2]*zoodata$y[nextOb-1]+coef(mod)[3]*zoodata$x[nextOb-1]
  
     #strip timeseries information
     attributes(predicted)&lt;-NULL
  
     return(predicted)
    }                
  
  rolling&lt;-rollapply(zoodata,width=40,FUN=prediction,by.column=FALSE)
  </code></pre>
  
  <p>This returns:</p>
  
  <pre><code>20          21      .....      80
  10.18676  10.18676          10.18676
  </code></pre>
  
  <p>Which has two problems I was not expecting:</p>
  
  <ol>
  <li>Runs from 20->80, not 40->100 as I would expect (as the width is 40)</li>
  <li>The forecasts it gives out are constant: 10.18676</li>
  </ol>
  
  <p>What am I doing wrong?  And is there an easier way to do the prediction than to write it all out?  Thanks!</p>