Stop an R program without error
You're looking for the function browser
.
Terminate the exectuion with STOP() but not throwing an Error message in R
This would hide the word "error" on the console but the program still sees it as an error. Referencing on Stop an R program without error
if (nrow(new_data) == 0) {
message(log_date, " - ","no new_data is found ")
opt <- options(show.error.messages=FALSE)
on.exit(options(opt))
stop()
}
else { # DO SOMETHING ELSE
}
How do I stop/end/halt a script in R?
As far as I could find, there is no single command that really stops a script on every platform/version. There are several ways to handle this:
Put it in a function or curly brackets:
{
if (TRUE) {stop("The value is TRUE, so the script must end here")}
print("Script did NOT end!")
}
OR evaluate the error and handle it like in an if else construction:
if (TRUE) {stop("The value is TRUE, so the script must end here")
} else { #continue the script
print("Script did NOT end!")
}
OR (EDIT):
Another possibility is to call the script from a seperate 'main' R-scipt, with source("MyScript.R")
. Then the script terminates. This however, suppresses all output other then errors to the console.
OR for more complex operations, use tryCatch()
as shown here
break/exit script
You could use the stopifnot()
function if you want the program to produce an error:
foo <- function(x) {
stopifnot(x > 500)
# rest of program
}
Make execution stop on error in RStudio / Interactive R session
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).
Stop executing code in R
According to stop
, it only stops evaluation of the current expression. While I agree with Roland's comment to encapsulate your code into meaningful pieces via functions, a quick hack would be to wrap all your current code in curly braces. That will make it appear to the R parser as a single expression.
R> # without curly braces
R> x <- 1
R> y <- 2
R> if (x < y)
+ stop("x < y")
Error: x < y
R> print("hello")
[1] "hello"
R>
R> # with curly braces
R> {
+ x <- 1
+ y <- 2
+ if (x < y)
+ stop("x < y")
+ print("hello")
+ }
Error: x < y
Stopping an R script without getting Error during wrapup message
I just found this inside R source code:
if (inError) {
/* fail-safe handler for recursive errors */
if(inError == 3) {
/* Can REprintf generate an error? If so we should guard for it */
REprintf(_("Error during wrapup: "));
/* this does NOT try to print the call since that could
cause a cascade of error calls */
Rvsnprintf(errbuf, sizeof(errbuf), format, ap);
REprintf("%s\n", errbuf);
}
stop()
causes the error handler to be executed. If the stop()
call occurs within the error handler, R displays the Error during wrapup:
message and prevents you from the infinite recursion that would occur otherwise.
Do not call stop()
from inside your options$error
.
Use q(save="no", status=1, runLast=FALSE)
instead, that should do exactly what the default error handler does for non-interactive use. See ?options
for the meaning of options$error
and ?stop
for details about error handling.
Calling stop( ) within function causes R CMD Check to throw error
Since your function has global side effects, I think check
isn't going to like it. It would be different if you required the user to put tryCatch
at the top level, and then let it catch the error. But think about this scenario: a user defines f()
and calls it:
f <- function() {
call_your_function()
do_something_essential()
}
f()
If your function silently caused it to skip the second line of f()
, it could cause a lot of trouble for the user.
What you could do is tell the user to wrap the call to your function in tryCatch()
, and have it catch the error:
f <- function() {
tryCatch(call_your_function(), error = function(e) ...)
do_something_essential()
}
f()
This way the user will know that your function failed, and can decide whether or not to continue.
From discussion in the comments and your edit to the question, it seems like your function is only intended to be used interactively, so the above scenario isn't an issue. In that case, you can avoid the R CMD check
problems by skipping the example unless it is being run interactively. This is fairly easy: in the help page for a function like create_directories()
, set up your example as
if (interactive()) {
create_directories()
# other stuff if you want
}
The checks are run with interactive()
returning FALSE
, so this will stop the error from ever happening in the check. You could also use tryCatch
within create_directories()
to catch the error coming up from below if that makes more sense in your package.
What function to interrupt the running R script?
The stop()
function returns an error if called, so you can use this. The only trick is that if you're using it in interactive mode, you need to wrap all the code that you want to skip in a set of braces, e.g.
df <- data.frame(one = c(1,2,NA,4,NA), two = c(NA,NA,8,NA,10))
{
if(sum(is.na(df)) > 3) stop("More than three NAs")
print("don't run this")
}
# Error: More than three NAs
Note the braces include the print line, otherwise stop would just carry on running the code after the line that causes an error, e.g.
if(sum(is.na(df)) > 3) stop("More than three NAs")
# Error: More than three NAs
print("don't run this")
# [1] "don't run this"
R stop() function not enforced within if else statement
I am assuming, that you are running this in an interactive R Session, probably RStudio. In that case when you run the whole file each line is being executed independently of the previous lines succeeding or failing. If you run the script from the operation system command line/ terminal instead, it will break at the stop()
, when the condition of the if()
statement is FALSE.
Try this, to see what happens when the condition is FALSE:
Rscript -e 'if(FALSE){print("Successful check, all good to proceed"}
else{print("Execution stopped. Check Table1");stop()};a<-1;a'
Try this, to see what happens when condition is TRUE:
Rscript -e 'if(TRUE){print("Successful check, all good to proceed"}
else{print("Execution stopped. Check Table1");stop()};a<-1;a'
To achieve the behaviour you are looking for you could execute your whole file from the operation system command line/ terminal with Rscript
or [edit:] just move the further code into the if statement
Something like this should work:
if (check_date == Sys.Date()) {
print("Successful check, all good to proceed")
# more code here
} else {
stop("Execution stopped. Check Table1")
}
}
Related Topics
Is There a Logical Way to Think About List Indexing
How to Use Multiple Versions of the Same R Package
Creating Regular 15-Minute Time-Series from Irregular Time-Series
How to Implement a Cleanup Routine in R Shiny
Insert Elements in a Vector in R
How to Use Data.Table Within Functions and Loops
Inputting Na Where There Are Missing Values When Scraping with Rvest
Greek Letters, Symbols, and Line Breaks Inside a Ggplot Legend Label
Only Download Sources of a Package and All Dependencies
Add Percentage Labels to a Stacked Barplot
Can Dplyr Join on Multiple Columns or Composite Key
MAC Os X R Error "Ld: Warning: Directory Not Found for Option"
Error in File(File, "Rt"):Cannot Open the Connection
Date Format in Tooltip of Ggplotly
Group by and Filter Data Management Using Dplyr
Counting the Frequency of an Element in a Data Frame
Combine Several Data Frames in the Global Environment by Row (Rbind)