Anakin Skywalker
Anakin Skywalker

Reputation: 2520

Error in window.default(x, ...) : 'start' cannot be after 'end' during cross-validation of VAR model in R

I have a dataframe with differenced data.

Data has format [1] "mts" "ts" "matrix"(tried "mts" "ts" too).

Data goes from March 2008 to August 2020 (150 values in total).

The sample dput of chicago_diff11 dataframe is the following:

structure(c(-4000, 3000, 1000, 5000, 3500, -3500, 0.0499999999999998, 
-0.0499999999999998, 0.12, 0.28, 0.109999999999999, 0.0500000000000007
), .Dim = c(6L, 2L), .Dimnames = list(NULL, c("Median_price_ts_diff1", 
"Average_rate_ts_diff1")), .Tsp = c(2008.16666666667, 2008.58333333333, 
12), class = c("mts", "ts", "matrix"))

I am trying to replicate the code from this question.

My current code looks like

# Forecast horizon
j <- 12

# Length of minimum training set
k <- nrow(chicago_diff11) - j 

# Create actual and prediction
prediction <- data.frame()
actual <- data.frame()

for (i in j) { 
  trainingset <- window(chicago_diff11, end = k+i-1)
  testset <- window(chicago_diff11, start = k-j+i+1, end = k+j)
  fit <- VAR(trainingset, p = 10)                       
  fcast <- forecast(fit, h = j)
  fcastmean <- do.call('cbind', fcast[['mean']])
  fcastmean <- as.data.frame(fcastmean)

  prediction <- rbind(prediction, fcastmean)
  actual <- rbind(actual, as.data.frame(testset[,1]))
}

# add predictions and actual values
result <- cbind(prediction, actual[, 1])
names(result) <- c("Predicted", "Actual")
result$Difference <- abs(result$Actual - result$Predicted)

# Use Mean Absolute Error as Evalution 
summary(result$Difference)

But this function breaks

Error in window.default(x, ...) : 'start' cannot be after 'end'

My data structure is the same as in the original question. What and where am I missing something? Thanks!

Upvotes: 0

Views: 1536

Answers (1)

kangaroo_cliff
kangaroo_cliff

Reputation: 6222

Your specification of end/start of window function is wrong. See an example below.

window(chicago_diff11, end = c(2008, 7))
         Median_price_ts_diff1 Average_rate_ts_diff1
Mar 2008                 -4000                  0.05
Apr 2008                  3000                 -0.05
May 2008                  1000                  0.12
Jun 2008                  5000                  0.28
Jul 2008                  3500                  0.11

Upvotes: 1

Related Questions