Search code examples
rhierarchyforecasting

R HTS package: combinef and aggts not working with gts object


I'm trying to apply the combinef and aggts functions from the R hts package to a time series matrix in order to obtain an optimized set of forecasts across a hierarchy. I've run the same code every month without issue, and am now seeing errors after upgrading to hts package v4.5.

Reproducible example (I can share data file offline if needed)

    #Read in forecast data for all levels of hierarchy#

fcast<-read.csv("SampleHierarchyForecast.csv", header = TRUE, check.names = FALSE)

#Convert to time series#

fcast<-ts(fcast, start = as.numeric(2010.25) + (64)/12, end = as.numeric(2010.25) + (75)/12, f= 12)

#Create time series of only the bottom level of the hierarchy#
index<-c()

fcastBottom<-fcast
for (i in 1:length(fcastBottom [1,]))
{
    if(nchar(colnames(fcastBottom)[i])!=28)
    index[i]<-i
    else
    index[i]<-0
}
fcastBottom<-fcastBottom[,-index]

#Create grouped time series from the bottom level forecast #
GtsForecast <- gts(fcastBottom, characters = list(c(12,12), c(4)), gnames = c("Category", "Item", "Customer", "Category-Customer"))
#Use combinef function to optimally combine the full hierarchy forecast using the groups from the full hierarchy gts#
combo <- combinef(fcast, groups = GtsForecast$groups)
*Warning message:
In mapply(rep, as.list(gnames), times, SIMPLIFY = FALSE) :
  longer argument not a multiple of length of shorter*
traceback()
2: stop("Argument fcasts requires all the forecasts.")
1: combinef(fcast, groups = GtsForecast$groups)

Solution

  • There's a little bug when comebinef() function calls gts(). Now I've fixed it on github. So you can run your own code above without any trouble after updating the development version.

    Alternatively, you need to tweak your code a bit if you don't want to install the newest version.

    combo <- combinef(fcast, groups = GtsForecast$groups, keep = "bottom")
    combo <- ts(combo, start = as.numeric(2010.25) + (64)/12, 
                end = as.numeric(2010.25) + (75)/12, f = 12)
    colnames(combo) <- colnames(fcastBottom)
    newGtsForecast <- gts(combo, characters = list(c(12,12), c(4)), 
                      gnames = c("Category", "Item", "Customer", 
                                 "Category-Customer"))
    Aggregate <- aggts(newGtsForecast)
    

    Hope it helps.