Home > Net >  Why I cannot assign a value to a variable in the error function of a tryCatch (R)?
Why I cannot assign a value to a variable in the error function of a tryCatch (R)?

Time:08-25

I am creating a webscraping script that sometimes requires me to raise exceptions when errors are encountered. However, it is quite common for Error Messages to pop up (although not interrupting the code) even with a tryCatch function. In order to eliminate these messages, I have used the suppressMessages function. However, when an error appears, I have specified a new value for a variable. However, it does not seem to get assigned. Why is this happening? I would like to have the same functionality as Python try and except.

The code is as follows:

tryCatch({suppressMessages(
                {found_university <- css_find(css_list$university)
                google_university <- found_university$getElementText()[[1]]}
              )
      },
          error = function(e){
                found_university <- ""
             })

However, if the error appears and I have not created a variable named found_university before executing it, the following error pops up:

Error: object 'found_university' not found

CodePudding user response:

The value does get assigned to a variable, but only inside the function you specified. This has to do with the scoping rules of R, see e.g. here

As suggested by @Roland, you could use <<- or .GlobalEnv.

But you can also use try:

ans <- try({
    your code
    }, silent=TRUE
)

if(inherits(ans, "try-error")) found_uni <- ""
  • Related