1

I have a variable declaration inside of an error function of a tryCatch function. But when the error is triggered, the variable declaration is not performed, even though the error message is successfully output.

tryCatch({ var_binned_names = arules::discretize(Xt,
                                              method = arules_method,
                                              breaks = num_breaks,
                                              ordered = TRUE)
        }, error = function(error) {
          cat("Error: could not discretize numeric", numeric_i, "", name, "\n")
          cat("Unique values:", length(unique(Xt)), "\n")
          var_binned_names = Xt
        })

One would expect that, when var_binned_names is failed to be assigned due to an error with discretize, that it would get assigned Xt in the error function. However, what happens is that it's not defined.

Hayden Y.
  • 440
  • 2
  • 8
tyur43
  • 11
  • 1
  • 1
    Because the variable is local? https://stackoverflow.com/questions/10904124/global-and-local-variables-in-r – user202729 Aug 19 '19 at 06:27
  • @user202729 thanks for your comment. is it the case that if the discretize function had run successfully and var_binned_names had been declared in the tryCatch function, this would then be a global assignment? – tyur43 Aug 19 '19 at 06:31
  • 1
    maybe move `var_binned_names = ` outside of `tryCatch`? – chinsoon12 Aug 19 '19 at 06:37

2 Answers2

1

Use this approach:

Xt <- 1

res <- tryCatch({ stop("some error")
}, error = function(error) {
  cat("some error message")
  Xt
})

res
#[1] 1

tryCatch has a return value. It is the return value of the expression or (if a condition such as an error is triggered) the return value of the handler.

Roland
  • 122,144
  • 10
  • 182
  • 276
0

The function has its own environment, so an assignment inside the function will not be made to the global environment. You can return the value and assign it outside the function or if you want to make an assignment to the parent environment inside of a function, then use <<- instead of <- or =.

shs
  • 1,998
  • 4
  • 24