Search code examples
rsmoothingforecasting

Forecast multiple columns with for-loop


I'm new with R (and programming), and I have to make as simple exponential smoothing forecast for 216 different products.

example:

items <- dataset 

Date     A      B      C  
01-10    3      1      7 
02-10    4      2      0  
03-10    9      2      1 
04-10    8      1      3  

I got:

for(i in 1:ncol(items)) { 
  col <- ts(items[,i]) 
  fcast <- ses(col, h=12) 
  write.table(fcast, file ="test.csv",sep=";", dec=",") 
} 

Error: not compatible with REALSXP

Am I doing everything wrong, or am I on the right track?... please help me


Solution

  • This should work:

    # library("forecast")
    for(i in 1:ncol(items)) { 
      col <- ts(items[,i]) 
      fcast <- ses(col, h=12) 
      write.table(fcast, file =paste("test", i, ".csv", sep="") ,sep=";", dec=",") 
    } 
    

    Althogh I didnt get any error with your code.

    For my example item is a data.frame look at dput output:

    structure(list(Date = structure(1:4, .Label = c("01-10", "02-10", 
    "03-10", "04-10"), class = "factor"), A = c(3L, 4L, 9L, 8L), 
        B = c(1L, 2L, 2L, 1L), C = c(7L, 0L, 1L, 3L)), .Names = c("Date", 
    "A", "B", "C"), class = "data.frame", row.names = c(NA, -4L))
    

    where the first column is factor and the others are integer