How do I stop/end/halt a script in R?

Note that in RStudio the

stop("Error message")

call actually stop the execution of the script after printing the error message.


Very simple: call a function that has not been declared:

condition <- TRUE
if (condition) {
  print('Reason for stopping')
  UNDECLARED()
}

And the script will stop with the messages:

[1] "Reason for stopping"
Error in UNDECLARED() : could not find function "UNDECLARED"

maybe it is a bit too late, but I recently faced the same issue and find that the simplest solution for me was to use:

quit(save="ask")

From ?quit you can see that:

save must be one of "no", "yes", "ask" or "default". In the first case the workspace is not saved, in the second it is saved and in the third the user is prompted and can also decide not to quit. The default is to ask in interactive use but may be overridden by command-line arguments (which must be supplied in non-interactive use).

You can then decide not to quit R by clicking on "cancel" when the message box pops-up.

Hope that helps!


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