ali ali - 2 months ago 16
R Question

How to create a forecast object in R

I have wrote a function that forecasts a time series object using different forecast methods like

forecast::nnetar
,
forecast::tbats
,
forecast::Arima
and
forecast::ets
.

I know that
forecastHybrid::hybridModel
function is doing this, I just wanted to create something more customized. So I am now returning a list with
result$mean
,
result$error
and
result$fit
. I want to use accuracy or plot function like forecast object. Is there a easy way to do that? or is it too complicated?

EDIT: About the function, it takes a
ts
object, an arima model-that I found by taking differences and checking ACF-PACF graphs- and a horizon to be forecasted. It applies
nnetar
,
ets
,
tbats
and my arima model.

It combines their fits and forecasts and create a new fit values and forecast values.

It returns a list object with forecasted values as
result$mean
(this is also same in forecast objects), fitted values as
result$fit
and errors as
result$error
.

Now with that returned object, I cant automate some series of works like having accuracy, making plots etc. So I want to return a forecast object if it is possible. that is what it is.

Answer

A forecast object is just a list containing a few items, and given a class "forecast". Look at any of the existing functions to see how to do it. Here is a very simple template:

myfun <- function(x, h, ...)
{
  # Compute some forecasts
  fc <- ....
  # Construct output list
  output <- list(mean=fc, x=x, ...)
  # Return with forecasting class
  return(structure(output, class='forecast'))
}
Comments