Search code examples
rholtwinters

Trying to figure out For Loops


I'm just trying to get the For loop to increment a rolling window with a 1 month increment and determine the HW parameters at each increment.

ss<-c(29,36,36,48,93,28,35,28,37,50,37,3,25,28,40,45,38,43,34,44,43,25,33,34)
ss2<-t(ss)
for (i in 1:12){
sseries<-ts(ss2[c(i:11+i)],frequency=12)
ssforecasts <- HoltWinters(sseries, beta=FALSE, gamma=FALSE)
ssforecasts
}

But I get :

Error in ts(cbind(xhat = final.fit$level[-len - 1], level = final.fit$level[-len - : 'ts' object must have one or more observations


Solution

  • You are calling a slice properly, but R's order of evaluation is not evaluating as you seem to want it to. When you get to i=11 you get this:

    > i:11+i
    [1] 22
    

    which is what is giving the error, try this instead:

    ss<-c(29,36,36,48,93,28,35,28,37,50,37,3,25,28,40,45,38,43,34,44,43,25,33,34)
    ss2<-t(ss)
    for (i in 1:12){
      sseries<-ts(ss2[c(i:(11+i))],frequency=12)
      ssforecasts <- HoltWinters(sseries, beta=FALSE, gamma=FALSE)
      ssforecasts
    }