How can I turn my ts forecast into a dataframe with date values?

Viewed 304

I am working on a forecasting model using arima that will need to be exported to a database. I need to turn my forecast into a dataframe. I have done so in an elaborate way, but am hoping there is something simpler so I don't have to hard code the dates in.

To get the forecast, I am creating a model "fit" and then running fcst1 <- forecast(fit, 4) to get four months worth, for example.

Here is the format of the result when I print my forecast:

         Point Forecast   Lo 80    Hi 80   Lo 95    Hi 95
Jan 2021       x
Feb 2021       x
Mar 2021       x
Apr 2021       x 

I am only wanting the point forecast, which I know I can get from forecast$mean, but I also want the date column. I'm also combining multiple forecasts (for different segments) into one table, so at the moment I am able to get my results by doing this:

months <- c('Jan-2021', 'Feb-2021', 'Mar-2021', 'Apr-2021')
forecasts <- as.data.frame(rbind(cbind(months, fcst1$mean, "Segment 1"), 
                            cbind(months, fcst2$mean, "Segment 2"),
                            cbind(months, fcst3$mean, "Segment 3"),
                            cbind(months, fcst4$mean, "Segment 4"),
                            cbind(months, fcst5$mean, "Segment 5"),
                            cbind(months, fcst6$mean, "Segment 6"),
                            cbind(months, fcst7$mean,"Segment 7")))

Which gives me the forecast results as three columns: the month, the forecast, and the segment.

    months       fcst$mean      "Segment"
1  Sep-2020           2        Segment 1
2  Oct-2020           1        Segment 1
3  Nov-2020           3        Segment 1
4  Dec-2020           2        Segment 1

However, for this to be repeatable in the future, it would be ideal if I didn't have to hard code in the months, and it could pull it from the forecast (since it's already there anyways). Is there a way to pull the dates from a ts object as a data frame column?

rownames(fcst1) returns as null and I haven't been able to find an answer to this on the internet. Thanks in advance!

*note: the dates are in yearmon format

1 Answers

If the objects are already created in the global environment, use mget to get the values in a list

Forecast <- sapply(mget(ls(pattern = '^fcst\\d+$')), function(x) x$mean)

Now, we use data.frame to construct a data.frame

data.frame(months, Forecast, Segment = paste0("Segment", seq_along(Forecast))))

To automatically get the months from the forecast object, use index

outlst <- lapply(mget(ls(pattern = '^fcst\\d+$')), function(x) 
        data.frame(months = index(x), Forecast = x$mean))
do.call(rbind, Map(cbind, outlst, Segment = paste("Segment", seq_along(outlst))))
Related