0

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?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
half-pass
  • 1,851
  • 4
  • 22
  • 33

1 Answers1

3

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)
}
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • But how would you go about when tryCatch isn't embedded into a function like in `safe_function` here? How would you make the variables defined within `tryCatch` accessible to the outer environment? – MJimitater Aug 02 '22 at 14:26
  • 1
    @MJimitater `tryCatch` will return a value whether or not it's called inside another function so I'm not sure what you are asking. Perhaps you can open your own new question if you have a different scenario. – MrFlick Aug 02 '22 at 14:52
  • Thanks @MrFlick, all is settled now - I was subject to the following quote by Norm Matloff: "Finding your bug is a process of confirming the many things that you believe are true — until you find one which is not true." – MJimitater Aug 02 '22 at 15:17