break/exit script

user2588829 picture user2588829 · Jul 24, 2013 · Viewed 145.4k times · Source

I have a program that does some data analysis and is a few hundred lines long.

Very early on in the program, I want to do some quality control and if there is not enough data, I want the program to terminate and return to the R console. Otherwise, I want the rest of the code to execute.

I've tried break,browser, and quit and none of them stop the execution of the rest of the program (and quit stops the execution as well as completely quitting R, which is not something I want to happen). My last resort is creating an if-else statement as below:

 if(n < 500){}
 else{*insert rest of program here*}

but that seems like bad coding practice. Am I missing something?

Answer

Michael Malick picture Michael Malick · Jul 24, 2013

You could use the stopifnot() function if you want the program to produce an error:

foo <- function(x) {
    stopifnot(x > 500)
    # rest of program
}