break/exit script

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?


如果您希望程序产生错误,您可以使用stopifnot()函数:

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

反转你的if-else结构:

if(n >= 500) {
  # do stuff
}
# no need for else

Edit: Seems the OP is running a long script, in that case one only needs to wrap the part of the script after the quality control with

if (n >= 500) {

.... long running code here

}

If breaking out of a function , you'll probably just want return() , either explicitly or implicitly.

For example, an explicit double return

foo <- function(x) {
  if(x < 10) {
    return(NA)
  } else {
    xx <- seq_len(x)
    xx <- cumsum(xx)
  }
  xx ## return(xx) is implied here
}

> foo(5)
[1] 0
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

By return() being implied, I mean that the last line is as if you'd done return(xx) , but it is slightly more efficient to leave off the call to return() .

Some consider using multiple returns bad style; in long functions, keeping track of where the function exits can become difficult or error prone. Hence an alternative is to have a single return point, but change the return object using the if () else () clause. Such a modification to foo() would be

foo <- function(x) {
  ## out is NA or cumsum(xx) depending on x
  out <- if(x < 10) {
    NA
  } else {
    xx <- seq_len(x)
    cumsum(xx)
  }
  out ## return(out) is implied here
}

> foo(5)
[1] NA
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55
链接地址: http://www.djcxy.com/p/24898.html

上一篇: R中的数据框和列表有什么区别?

下一篇: 休息/退出脚本