Stop an R program without error

前端 未结 9 1632
执笔经年
执笔经年 2020-12-01 10:35

Is there any way to stop an R program without error?

For example I have a big source, defining several functions and after it there are some calls to the functions.

9条回答
  •  孤街浪徒
    2020-12-01 11:21

    I found a rather neat solution here. The trick is to turn off all error messages just before calling stop(). The function on.exit() is used to make sure that error messages are turned on again afterwards. The function looks like this:

    stop_quietly <- function() {
      opt <- options(show.error.messages = FALSE)
      on.exit(options(opt))
      stop()
    }
    

    The first line turns off error messages and stores the old setting to the variable opt. After this line, any error that occurs will not output a message and therfore, also stop() will not cause any message to be printed.

    According to the R help,

    on.exit records the expression given as its argument as needing to be executed when the current function exits.

    The current function is stop_quietly() and it exits when stop() is called. So the last thing that the program does is call options(opt) which will set show.error.messages to the value it had, before stop_quietly() was called (presumably, but not necessarily, TRUE).

提交回复
热议问题