Creating a One-Day-Ahead Roll-Forward Forecast in R

637 views Asked by At

I am attempting to compute the predictive measures for roll-forward one-day-ahead forecasts and plot the results.

I had a few questions about my example code below:

  • What can I do to resolve the "replacement has length zero" error below?
  • How can I output an array of the prediction values for their respective dates?
  • How can I plot the data and the predictions on one graph?

This is the error received upon execution of the script:

Error in error[j - fixed.nTrain + 1] <- valid.ts - naive.pred$mean[stepsAhead] : replacement has length zero

The reproducible example is as follows.

d <- structure(list(Date = structure(c(17349, 17350, 17351, 17352, 
                                       17353, 17354, 17355, 17356, 17357, 17358, 17359, 17360, 17361, 
                                       17362, 17363, 17364, 17365, 17366, 17367, 17368, 17369, 17370, 
                                       17371, 17372, 17373, 17374, 17375, 17376, 17377, 17378, 17379, 
                                       17380, 17381, 17382, 17383), class = "Date"), Ratio = c(67, 50, 
                                                                                               67, 50, 100, 50, 33, 67, 0, 0, 0, 0, 100, 75, 0, 0, 75, 100, 
                                                                                               67, 33, 33, 33, 50, 50, 67, 100, 67, 50, 25, 25, 33, 33, 100, 
                                                                                               33, 0)), .Names = c("Date", "Ratio"), row.names = 183:217, class = "data.frame")

library(xts)
dates = as.Date(d$Date,"%Y-%m-%d")
xs = xts(d$Ratio,dates)

library("forecast")
fixed.nValid <- 6
fixed.nTrain <- length(xs) - fixed.nValid
stepsAhead <- 2
error <- rep(0, fixed.nValid - stepsAhead + 1)
percent.error <- rep(0, fixed.nValid - stepsAhead + 1)
predictions <-rep(0, fixed.nValid - stepsAhead + 1)
for (j in fixed.nTrain:(fixed.nTrain + fixed.nValid - stepsAhead)) {
  train.ts <- window(xs, start = as.Date("2017-07-02"), end = as.Date("2017-07-02") + j)
  valid.ts <- window(xs, start = as.Date("2017-07-02") + j + stepsAhead, end = as.Date("2017-07-02") + j + stepsAhead)
  naive.pred <- naive(train.ts, h = stepsAhead)
  error[j - fixed.nTrain + 1] <- valid.ts - naive.pred$mean[stepsAhead]
  percent.error[j - fixed.nTrain + 1] <- error[j - fixed.nTrain + 1] / valid.ts
}
mean(abs(error))
sqrt(mean(error^2))
mean(abs(percent.error))

This is the output of the script above:

enter image description here

Thank you!

1

There are 1 answers

2
Robert On BEST ANSWER

The problem is that, when j = 33 in your for-loop, the value of

as.Date("2017-07-02") + j + stepsAhead

is "2017-08-06", which is later than the latest date in xs. This results in valid.ts having zero length, which is causing the error you're seeing.