2
for(i in 2:num_asset){
  assetclass <- ts(mydt[,i])
  tryCatch(
    {
      fit <- Arima(assetclass,order = c(2,0,2))
    },
    error = function(e){
      fit <- auto.arima(assetclass)
      k=i
    }
  )
  fst <-as.data.frame(forecast(fit, h=52))
}

I want to run code above. But It doesn't work showing message below.

Error in forecast(fit, h = 52) : object 'fit' not found

My intention is ... If there is an error in first function( fit <- Arima(assetclass,order = c(2,0,2)) ) then, I'd like to run second function(fit <- auto.arima(assetclass))

How should I do?

Jaap
  • 81,064
  • 34
  • 182
  • 193
GS SHIN
  • 53
  • 5

1 Answers1

1

The immediate cause of your error is that the following line is referring to the fit variable, which does not exist in the scope in which it is being referenced:

fst <- as.data.frame(forecast(fit, h=52))

One option would be to just have the try catch return the value of fit, whatever it be based on success or error:

for (i in 2:num_asset) {
    assetclass <- ts(mydt[,i])
    fit <- tryCatch({
        return(Arima(assetclass,order = c(2,0,2)))

    }, error = function(e) {
        k=i
        return(auto.arima(assetclass))
    })

    fst <- as.data.frame(forecast(fit, h=52))
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360