23

When executing a block of code in RStudio, execution doesn't actually stop when an error occurs. For example, if I have the following code in the open editor:

x <- 'test'
stopifnot(is.numeric(x))
print('hello world')

And run it (either with command-return or by clicking the "Run" button), it prints the error but then marches on and executes the print statement.

Is there a way to configure RStudio to not proceed past the error? i.e. make it stop at line 2 above and not proceed to the print statement?

EDIT: Just realized this also happens if I'm sending blocks of code in the standard R GUI using command-R.

8
  • If you execute this as a source file, then it will work as you want it to. If you, for example copy and paste the 3 lines of code into the console and hit Enter, then it will run each line of code separately. This second mode is likely what the Run button operates under.
    – lmo
    Feb 15, 2017 at 17:44
  • 1
    @lmo thanks -- the problem is most people I know program interactively. I'm trying to write a tutorial for social scientists to put tests in their code, and need to meet them where they are.
    – nick_eu
    Feb 15, 2017 at 17:46
  • There's always tryCatch and try.
    – lmo
    Feb 15, 2017 at 17:48
  • 6
    One hack I just thought of thanks to @Dason's comment: If you wrap the code in curly brackets, {} R will execute the block as if it were a single command, then you will get your desired result.
    – lmo
    Feb 15, 2017 at 17:52
  • 1
    @Dason it comes up in data science a lot. People have long scripts for data cleaning and organization, and want to add integrity checks to make sure when they change things at one point, it doesn't screw up their data elsewhere. Just little checks to make sure number of observations is still right, or the a unique identifier is still unique.
    – nick_eu
    Feb 15, 2017 at 17:53

4 Answers 4

6

One way to solve this is to configure the R 'error' option to run a custom function when an error is encountered.

An example error-handling function can pause execution of R using Sys.sleep and await user input (for instance, breaking-out of the running function by pressing ctrl-C, or Escape in R-Studio on my Mac).

Normally, R will then move-on and execute any subsequent commands. However, we can prevent this by defining a function that will 'eat' all of these so that they don't get run. To make this slicker-still, we can output a 'cursor up' character sequence after each 'eaten' line, which erases each of them as the next one is output, so that the not-run lines don't clutter up the terminal/console.

Example code:

# Define our error-handling pause function:

pause=function(){
    on.exit(eat_input())
    cat("Paused: press ctrl-C (or Escape key in Rstudio) to continue\n")
    cat("(any subsequent code will be ignored)\n")
    Sys.sleep(Inf)
}

# Define our 'eat_input' function to prevent output of subsequent, not-run input:

eat_input=function(){
    cat("\033[1A")
    while((x=readline())!='')cat("\033[1A")
}

# Set the 'error' option to execute our pause function:

options(error=pause)

Try it out:

print("Before the error")

# an error: we want to stop after this
xxx

# some more input: we don't want this to be run or to appear in the console
print("After the error")

To switch-off this behaviour, just re-set the error option to NULL:

options(error=NULL)
0
4

I don't think that there is a way to prevent RStudio from running all the lines, when you select a section and press Ctrl+Enter. Rstudio is just running one line after the other. Even if stopifnot() is called inside of a function, all the lines after that function call will still be evaluated.

If your goal is simply to be informed when something goes wrong, before a lot of code is run in vain, maybe you could define a function similar to stopifnot() that will just go into an endless loop, if there is an error. You could then press Esc or the Stop-Button in RStudio to interrupt the program. Something like this:

waitifnot <- function(cond) {
  if (!cond) {
    message(deparse(substitute(cond)), " is not TRUE")  
    while (TRUE) {}
  }
}

Now, you can run your example code with this function:

x <- 'test'
waitifnot(is.numeric(x))
print('hello world')

As expected, hello world is never printed. You will get an error message, telling you that something went wrong, and then the program will wait until you abort it manually.

This won't work well in any situation other than interactive mode. To avoid unpleasant situations, you could also let the function react differently, if it is not used in interactive mode, for instance like this:

waitifnot <- function(cond) {
  if (!cond) {
    msg <- paste(deparse(substitute(cond)), "is not TRUE")
    if (interactive()) {
      message(msg)
      while (TRUE) {}
    } else {
      stop(msg)
    }
  }
}

This function will go into an endless loop only if run in interactive mode. Otherwise, it will simply abort execution by calling stop(). I have checked that this works as expected with Ctrl+Enter or the Source button in RStudio (endless loop) and with Rscript on the Bash command line (abort of the program).

0
3

One way I solved this is by including all the code that could possibly fail inside a function and then just call that single function in a source file. So, Instead of having this:

print('before error')
failing_function()
print('after error')

do this

code_that_stops_with_error <- function(){
print('before error')
failing_function()
print('after error')
}
code_that_stops_with_error()
1

As mentioned by @lmo, you just need to hit the button Source instead of select all + Run. In fact, you don't even need to save the script file to be able to hit the Source button.

But the problem indeed is that Source will always run the entire script. So if you really only want to run a block within the script, this won't help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.