Home > database >  How can I get RStudio to continue executing code after encountering an error
How can I get RStudio to continue executing code after encountering an error

Time:07-12

I am using RStudio on Mac and like to highlight a chunk of code and hit Command Return to get this chunk to run. For some reason, when I do this now, the code stops running when an error appears. How can I get it to go back to the way it used to be when all of the lines would run even if a previous line returned an error?

CodePudding user response:

Possible duplicate of: How to ignore error while running r script.

The easiest method is to use the tryCatch() function. As explained in detail here: Debugging, condition handling, and defensive programming

A good example of the syntax is given here: How to write trycatch in R. As shown:

result = tryCatch({
    expr
}, warning = function(warning_condition) {
    warning-handler-code
}, error = function(error_condition) {
    error-handler-code
}, finally={
    cleanup-code
})

You can test it like this:

result <- tryCatch({1==0}, error=function(e) e)
if (inherits(result, "error")) {
  print("There was an error")
} else {
  # pass through, there was no error.
}

Here is a good example of how to implement this tryCatch() in to a function: github/cran/seastests/R/qs.R.

CodePudding user response:

It sounds as though your shortcut may be bound to the source execution method, which executes the file as a whole, instead of the interactive run. You may need to check or update your shortcuts.

  • Related