break/exit script

前端 未结 8 1269
Happy的楠姐
Happy的楠姐 2021-01-30 15:22

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 enou

8条回答
  •  时光取名叫无心
    2021-01-30 16:13

    This is an old question but there is no a clean solution yet. This probably is not answering this specific question, but those looking for answers on 'how to gracefully exit from an R script' will probably land here. It seems that R developers forgot to implement an exit() function. Anyway, the trick I've found is:

    continue <- TRUE
    
    tryCatch({
         # You do something here that needs to exit gracefully without error.
         ...
    
         # We now say bye-bye         
         stop("exit")
    
    }, error = function(e) {
        if (e$message != "exit") {
            # Your error message goes here. E.g.
            stop(e)
        }
    
        continue <<-FALSE
    })
    
    if (continue) {
         # Your code continues here
         ...
    }
    
    cat("done.\n")
    

    Basically, you use a flag to indicate the continuation or not of a specified block of code. Then you use the stop() function to pass a customized message to the error handler of a tryCatch() function. If the error handler receives your message to exit gracefully, then it just ignores the error and set the continuation flag to FALSE.

提交回复
热议问题