简体   繁体   中英

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:

Error: object 'found_university' not found

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 eg 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 <- ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM