I have a for loop in which I need to perform the forecast for different values passed by the parameter i, when there are errors in the Holtwinters Forecast, often optimization failure, the loop is interrupted. How can I make my code just skip the error ones and go to the next i and continue the operations in the loop. For example, if I run the code below, the loop will be interrupted when i=2 by the error: Error in HoltWinters(TS[[i]]) : optimization failure
What I need is when the error is found, it automatically move to i=3 and continue the operations rather than being interrupted, like "continue" in C++
Could someone pls kindly help with that ?
Thank you.
data <- list()
data[[1]] <- rnorm(36)
data[[2]] <-
c(
24,24,28,24,28,22,18,20,19,22,28,28,28,26,24,
20,24,20,18,17,21,21,21,28,26,32,26,22,20,20,
20,22,24,24,20,26
)
data[[3]] <- rnorm(36)
TS <- list()
Outputs <- list()
for (i in 1:3) {
TS[[i]] <- ts(data[[i]], start = 1, frequency = 12)
Function <- HoltWinters(TS[[i]])
TSpredict <- predict(Function, n.ahead = 1)[1]
Outputs[[i]] <-
data.frame(LastReal = TS[[i]][length(TS[[i]])], Forecast = TSpredict)
}
You can use tryCatch to skip the iteration with the error.
for (i in 1:3)
tryCatch({
TS[[i]] <- ts(data[[i]], start = 1, frequency = 12)
Function <- HoltWinters(TS[[i]])
TSpredict <- predict(Function, n.ahead = 1)[1]
Outputs[[i]] <-
data.frame(LastReal = TS[[i]][length(TS[[i]])], Forecast = TSpredict)
}, error=function(e){})
If you want to display an error message during the failed iteration and run the entire code you can use:
for (i in 1:3)
tryCatch({
TS[[i]] <- ts(data[[i]], start = 1, frequency = 12)
Function <- HoltWinters(TS[[i]])
TSpredict <- predict(Function, n.ahead = 1)[1]
Outputs[[i]] <-
data.frame(LastReal = TS[[i]][length(TS[[i]])], Forecast = TSpredict)
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})