title: Cross validate seasonal linear model
body: <p>I'm trying to perform a CV on my linear model, which has seasonal dummy variables, so i can't take a random sample.</p>
  
  <pre><code>y = rnorm(120,0,3) + 20*sin(2*pi*(1:120)/12) 
  x = months(ISOdate(2012,1:12,1))
  reg.data = data.frame(y, x)
  model = lm(y ~ x, data = reg.data)
  </code></pre>
  
  <p>My CV function is:</p>
  
  <pre><code>cross.valid = function(model, min.fit = as.integer(nrow(model$model)*0.7), h = 1)
  {
    dados = model$model
    n.rows = nrow(dados)
  
    results = data.frame(pred = numeric(), actual = numeric())
  
    for (i in seq(1, n.rows - min.fit - h + 1, by = h))
    {
     dados.train = dados[1:(i + min.fit - 1), ]
     model &lt;- update(model, data = dados.train)
  
     dados.pred = dados[(i + min.fit):(i + min.fit + h - 1), -1, drop = FALSE]
  
     predic = predict(model, newdata = dados.pred, interval = 'prediction')
     actual = dados[(i + min.fit):(i + min.fit + h - 1), 1]
     results = rbind(results, data.frame(pred = predic[1:h, 'fit'], actual = actual))
    }
  
    results
  }
  </code></pre>
  
  <p>Example:</p>
  
  <pre><code>cv1 = cross.valid(model, h = 1)
  mae = with(cv1, mean(abs(actual - pred )))
  print(mae)
  </code></pre>
  
  <p>The MAE values for different horizons (<em>h</em>) are too close. Is the code itself valid? Is there a better solution/package for doing this?</p>
  
  <p>Thanks!</p>