title: For loop AR model
body: <p>I want to do a n step ahead forecast with a AR(4) model with a differenced time series.</p>
  
  <p><strong>The model itself:</strong></p>
  
  <pre><code>X(t)-X(t-1)=a(1)(X(t-1)-X(t-2))+...+a(4)(X(t-4)-X(t-5))
  
  =&gt; X(t)=X(t-1)+a(1)(X(t-1)-X(t-2))+...+a(4)(X(t-4)-X(t-5))
  </code></pre>
  
  <p><strong>First forecast:</strong></p>
  
  <pre><code>X(t+1)-X(t)=a(1)(X(t)-X(t-1))+...+a(4)(X(t-3)-X(t-4))
  
  =&gt; X(t+1)=X(t)+a(1)(X(t)-X(t-1))+...+a(4)(X(t-3)-X(t-4))
  </code></pre>
  
  <p><strong>Second forecast:</strong></p>
  
  <pre><code>X(t+2)-X(t+1)=a(1)(X(t+1)-X(t))+...+a(4)(X(t-2)-X(t-3))
  
  =&gt; X(t+2)=X(t+1)+a(1)(X(t+1)-X(t))+...+a(4)(X(t-2)-X(t-3))
  </code></pre>
  
  <p>I tried it already with this <strong>code</strong>:</p>
  
  <pre><code>N&lt;-50
  arkoef&lt;-0
  ar&lt;-0
  ARforecast&lt;-numeric(0)
  arkoef&lt;-c(closingkursu[2518],closingkursu[2517],closingkursu[2516],closingkursu[2515],closingkursu[2514])
  ar&lt;-arkoef
  for(i in 1:N){
  ARforecast&lt;-c(ARforecast,arkoef[1]+arfit$coef[1]*(arkoef[1]-arkoef[2])+arfit$coef[2]*(arkoef[2]-arkoef[3])+arfit$coef[3]*(arkoef[3]-arkoef[4])+arfit$coef[4]*(arkoef[4]-arkoef[5]))
  ar = c(tail(ARforecast, 1), head(ar, -1))}
  </code></pre>
  
  <p>The output for this code is:</p>
  
  <pre><code>ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1 
  10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 
       ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1 
  10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 
       ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1 
  10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 
  </code></pre>
  
  <p>The first forecast seems right but the loop isnt working.</p>