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).
tryCatch
andtry
.{}
R will execute the block as if it were a single command, then you will get your desired result.