Potem29
Potem29

Reputation: 23

Timeseries Crossvalidation in R: using tsCV() with tslm()

I am trying to evaluate a tslm-model using time series cross validation I am using the very simple code below (based on what Rob Hyndman posted on here some years ago), but I only get NAs as a result. What is the issue with the code? I must be missing something on how the tscv() function works

y = ts(rnorm(336),frequency=12)

fc <- function(y, h, xreg)
{
  if(NROW(xreg) < length(y) + h)
    stop("Not enough xreg data for forecasting")
  X <- xreg[seq_along(y),]
  fit <- tslm(y ~ X)
  X <- xreg[length(y)+seq(h),]
  forecast(fit, newdata=X)
}

 
pred <- ts(rnorm(length(y)), start=start(y),
           frequency=frequency(y))


tsCV(y, fc, xreg=pred)

  Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
2   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
3   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
4   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
5   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
6   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
7   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
8   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
9   NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
10  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
11  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
12  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
13  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
14  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA

Upvotes: 2

Views: 56

Answers (1)

runr
runr

Reputation: 1146

Maybe it's better to examine the updated code from tsCV help pages. I.e.,

# Example with exogenous predictors
far2_xreg <- function(x, h, xreg, newxreg) {
  forecast(Arima(x, order=c(2,0,0), xreg=xreg), xreg=newxreg)
}

y <- ts(rnorm(50))
xreg <- matrix(rnorm(100),ncol=2)
e <- tsCV(y, far2_xreg, h=3, xreg=xreg)

If you want to work directly with your example, it needs some corrections to work:

fc <- function(y, h, xreg, newxreg)
{
  X <- xreg
  fit <- tslm(y ~ X)
  forecast(fit, newdata=X, xreg=newxreg)
}


pred <- ts(rnorm(length(y)), start=start(y),
           frequency=frequency(y))


tsCV(y, fc, xreg=pred, h = 3)

Upvotes: 0

Related Questions