Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error: object ‘found_university’ not found

>Solution :

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 <- ""
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading