How to exit R script source

Is there a function to exit the current R script, but not exit the entire execution?

I mean, in this situation:

for (i in ...) { ... source("model.R") } 

In the model.R file model.R I need an exit function that will complete the output of model.R :

 ... exit ... 

So stop and stopifnot cannot be considered ...

+6
source share
3 answers

It seems like the easiest solution is to wrap all the code in the script source code in a loop, and then break it:

model.R (sourced script):

 repeat { ... break # this will exit the sourced script ... break # just to prevent infinite loop in case the above break is removed } 

Thanks to Joshua Ulrich for his inspiration (he suggested using the function).

+2
source

It seems unusual to me to use the source in this way - it fills the environment from which it is launched, with any characters that it assigns, so several calls to the source can easily have unforeseen side effects. Instead, I will follow @ JoshuaUlrich's recommendations and formulate the script as a function (reusable, perhaps more modular). But for what it's worth, create and report a "condition" in "model.R"

 cond = structure(list(message="I'm done"), class=c("exit", "condition")) signalCondition(cond) 

and catch while searching

 tryCatch(source("model.R"), exit=function(cond) { message("finished because:", conditionMessage(cond)) }) 

Minimize changes to model.R by defining exit()

 exit <- function(message=character(), class="exit") { cond <- structure(list(message=message), class=c(class, "condition")) signalCondition(cond) } for (i in 1:5) { ## model.R simply invokes exit() or exit("I'm done") or exit(class="alt") ## if tryCatch wanted to handle conditions of class 'alt', too. tryCatch(source("model.R"), exit=message) } 

I think the invokeRestart() solution is more straight forward; merit above - the ability to indicate the reason for the early exit.

+6
source

One option is to use invokeRestart in the source file and end the call to source with withRestarts . For instance:

 t <- tempfile() write(file=t, " message('source A') invokeRestart('terminate') message('source B') ") for (i in 1:3) { message(i) if (i == 2) withRestarts(source(t), terminate=function() message('terminated')) } # 1 # 2 # source A # terminated # 3 unlink(t) 
+4
source

Source: https://habr.com/ru/post/973830/


All Articles