R: Exit the calling function

Is there a way in R to exit the calling function and return a value? Something like return() , but from a parent function?

 parent <- function(){ child() # stuff afterward should not be executed } child <- function(){ returnFromParent("a message returned by parent()") } 

It seems that stop() does something similar. I want to make a small replacement for stop() , which returns the message that stop() writes to stderr .

Update after the G5W proposal: I have a large number of checks, each of which leads to stop() if the test fails, but the following conditions cannot be evaluated if previous checks are not performed, so the function should exit after unsuccessful. To do this โ€œcorrectly,โ€ I would have to create a huge if else that I wanted to avoid.

+6
source share
3 answers

Got it. I think I was looking for something like this:

 parent <- function(){ parent_killing_child() print("do not run this") } parent_killing_child <- function(){ do.call(return, list("my message"), envir = sys.frame(-1)) } parent() 

Thanks for all the tips.

+5
source

Disclaimer This sounds like an XY problem, printing a stop message in stdout is of little importance, if interactive it shouldn't be a problem, if the script just uses the usual 2 > &1 redirection to write stderr messages to stdout or use sink as in the answer to this question .

Now, if I correctly understood what you are after, I will do something like the following to avoid too much code refactoring.

First, define a function to handle errors:

 my_stop <- function() { e <- geterrmessage() print(e) } 

Now configure the system to send errors to your function (error handler) and suppress the error messages:

 options(error = my_stop) options(show.error.messages=FALSE) 

Now let's test it:

 f1 <- function() { f2() print("This should not be seen") } f2 <- function() { stop("This is a child error message") } 

Output:

 > f1() [1] "Error in f2() : This is a child error message\n" 
+2
source

For the parent function, create a test list. Then run the test loop and return the message on the first failed test. Subsequent tests will not be performed after the first failure.

Code example:

 test1 <- function(){criteria <- T; return(ifelse(criteria,T,F))} test2 <- function(){criteria <- F; return(ifelse(criteria,T,F))} test3 <- function(){criteria <- T; return(ifelse(criteria,T,F))} parent <- function() { tests <- c('test1', 'test2', 'test3') for (i in 1:length(tests)) { passed <- do.call(tests[i],args = list()) #print(passed) if (!passed){ return(paste("Testing failed on test ", i, ".", sep='')) } } return('Congrats! All tests passed!') } parent() 
+1
source

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


All Articles