Error when populating matrix
<p>My question relates to populating the <code>mae</code> matrix below with the mean average error gotten by comparing <code>fcastmean</code> to the <code>testData</code>. </p>

<p>When running the for loop, the following error message comes up:</p>

<pre><code>Error in mae[i,1:length(testIndexes)] &lt;- (fcastmean - testData):
  replacement has length zero
</code></pre>

<p>In addition to this, there are some niggles that work, but which I feel need tidying up but am not sure how to. Namely the turning of <code>testData</code> and <code>trainData</code> into objects of class <code>mts</code>.</p>

<p>This is of course a secondary problem.</p>

<pre><code>library("forecast")
library("vars")

#Create dataset for test purposes
d &lt;- rnorm(70)
x &lt;- rnorm(70)

dx &lt;- cbind(d,x)
Data &lt;- as.ts(dx)

k  &lt;- 10 #Number of folds

mae &lt;- matrix(NA,length(d)/k,k) #Create mae matrix

#Randomly shuffle the data
Data&lt;-Data[sample(nrow(Data)),]

#Create k equally size folds
folds &lt;- cut(seq(1,nrow(Data)),breaks=k,labels=FALSE)

#Perform k fold cross validation
for(i in 1:k){
  #Segement data by fold
  testIndexes &lt;- which(folds==i,arr.ind=TRUE)
  testData &lt;- Data[testIndexes, ]
  testData &lt;- as.ts(testData)
  trainData &lt;- Data[-testIndexes, ]
  trainData &lt;- as.ts(trainData)

  #Use the test and train data partitions
  fit2 &lt;- VAR(trainData, p = 2)                       
  fcast &lt;- forecast(fit2, h = length(testIndexes))
  fcastmean &lt;- do.call('cbind', fcast[['mean']])
  mae[i,1:length(testIndexes)] &lt;- (fcastmean - testData)
}
</code></pre>

<p>Any suggestions would be appreciated</p>

<p><strong>Edit</strong></p>

<p>I have partially resolved my above question by applying the following solution:</p>

<pre><code>y &lt;- length(d)/k

m1 &lt;- matrix(NA, y, y)
m2 &lt;- matrix(NA, y, y)
</code></pre>

<p>and in the for loop:</p>

<pre><code>m1[i,1:length(testIndexes)] &lt;- (testData[,1]) 
m2[i,1:length(testIndexes)] &lt;- (fcastmean[,1]) 
</code></pre>

<p>followed by</p>

<pre><code>mae &lt;- m2-m1
</code></pre>

<p>After the loop.</p>

<p>However, while the matrix is created, the code only fills in <code>k</code> number of rows, rather than the number specified by `length(testIndexes).</p>

<p>Why is this?</p>

<p><strong>Edit 2</strong></p>

<p>It would appear the reason is that it only prints <code>i</code> iterations which is the same as <code>k</code>. However, the number of rows in the matrix needs to reflect the full forecast horizon, ie. <code>length(testIndexes)</code>.</p>

<p>How can this be resolved?</p>