Search code examples
renvironment-variablesglobal-variablescranscoping

How to use tryCatch without global variables or superassignment


I am writing an R package with a tryCatch() loop of the following form, in which I first try to fit a model using an error-prone method but then use a safer method if the first fails:

# this function adds 2 to x
safe_function = function(x) {

  tryCatch( {
    # try to add 2 to x in a stupid way that breaks
    new.value = x + "2"

  }, error = function(err) {
           message("Initial attempt failed. Trying another method.")
           # needs to be superassignment because inside fn
           assign( x = "new.value",
                  value = x + 2,
                  envir=globalenv() )
         } )

  return(new.value)
}

safe_function(2)

This example works as intended. However, the use of assign triggers a note when checking the package for CRAN-readiness:

Found the following assignments to the global environment

A similar problem happens if I replace assign with <<-. What can I do?


Solution

  • I'm not sure why you are trying to use the global scope here. You can just return the value from the try/catch.

    safe_function = function(x) {
    
      new.value <-   tryCatch( {
        # try to add 2 to x in a stupid way that breaks
        x + "2"
      }, error = function(err) {
        message("Initial attempt failed. Trying another method.")
        x + 2
      } )
    
      return(new.value)
    }