Avoid "optimization failure" for loop in R

I am trying to make a lot of time series predictions using the HoltWinters function in R. For this purpose I am using a for loop and internally I call the function and store the prediction in data.frame.

The problem is that some of the results of the HoltWinters function give errors, in particular optimization errors:

Error en HoltWinters(TS[[i]]) : optimization failure

      

This error aborts the loop.

So I need something like "try": if it can make the HoltWinters function, it stores the prediction, otherwise it stores the error.

The code below replicates the issue:

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)
}

      

Where I am <- 2 The problem is given.

I need the Outputs list in this example to be as follows:

> Outputs
[[1]]
   LastReal  Forecast
1 0.5657129 -2.274507

[[2]]
  LastReal Forecast
1    error    error

[[3]]
   LastReal   Forecast
1 0.4039783 -0.9556881

      

Thanks in advance.

+3


source to share


1 answer


I ran into this problem the other day with HoltWinters and took roman advice using tryCatch

. This is not the most intuitive implementation based on the documentation, but I found this link very helpful in understanding it: How to write a trycatch in R

My solution is sample-based.

    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()
result <- list()

for (i in 1:3) {
  Outputs[[i]] <- tryCatch({
    #You can enter messages to see where the loop is
    #message(paste("Computing", i))
    TS[[i]] <- ts(data[[i]], start = 1, frequency = 12)
    Function <- HoltWinters(TS[[i]])
    TSpredict <- predict(Function, n.ahead = 1)[1]
    result[[i]] <-
      data.frame(LastReal = TS[[i]][length(TS[[i]])], Forecast = TSpredict)
  },
  error = function(cond) {
    #message(paste("ERROR: Cannot process for time series:", i))
    msg <- data.frame(LastReal = "error", Forecast = "error")
    return(msg)
  })
}

      



And for exits

> Outputs
[[1]]
   LastReal  Forecast
1 0.4733632 0.5469373

[[2]]
  LastReal Forecast
1    error    error

[[3]]
   LastReal   Forecast
1 0.8984626 -0.5168826

      

You can use other error handling options such as finally

and warning

to deal with other exceptions that may be thrown.

+1


source







All Articles