Stop an R program without error

前端 未结 9 1548
执笔经年
执笔经年 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:10

    I have a similar problem and, based on @VangelisTasoulas answer, I got a simple solution.
    Inside functions, I have to check if DB is updated. If it is not, stop the execution.

    r=readline(prompt="Is DB updated?(y/n)")
    Is DB updated?(y/n)n
    if(r != 'y') stop('\r Update DB')
    Update DB
    

    Just putting \r in the beginning of the message, overwrite Error: in the message.

    0 讨论(0)
  • 2020-12-01 11:11

    Just return something at the line you want to quit the function:

    f <- function(x, dry=F) { 
       message("hi1")
       if (dry) return(x)
       message("hi2")
       x <- 2*x 
    }
    y1 <- f(2) # = 4 hi1 hi2
    y2 <- f(2, dry=T) # = 2 hi1
    
    0 讨论(0)
  • 2020-12-01 11:17

    There is a nice solution in a mailing list here that defines a stopQuietly function that basically hides the error shown from the stop function:

    stopQuietly <- function(...) {
      blankMsg <- sprintf("\r%s\r", paste(rep(" ", getOption("width")-1L), collapse=" "));
      stop(simpleError(blankMsg));
    } # stopQuietly()
    
    > stopQuietly()
    
    0 讨论(0)
  • 2020-12-01 11:17

    You can use the following solution to stop an R program without error:

    if (justUpdate)
        return(cat(".. Your Message .. "))
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-01 11:24

    just do quit() where you want the code to exit. It happens quietly.

    0 讨论(0)
提交回复
热议问题