user3673901
user3673901

Reputation: 31

R: stop a function within another function

I am working on a code and ran into a problem I can't seem to fix. Basically the idea is that I have one overall function and within that function are several other functions. My problem is: within one of those function I need the option to stop if a certain condition is not satisfied, but using stopifnot() of if (...) {stop} stops the overall functions as well. Is there a way in which I can stop the specific function from running without also stopping the overall function?

For example:

full=function(){

  message("before")
  x=2
  small=function(x){
    if (x<3){stop("smaller than 3")
    print(x)
  }
}

  small(x)
  message("after") 
  }
  full()

What I want to do here is quit the "small" function if x is smaller than 3 (so x is not printed), but I still want to run the message "after". Is there a way to do that?

Thanks in advance.

Upvotes: 3

Views: 561

Answers (1)

gagolews
gagolews

Reputation: 13046

Perhaps you are just looking for the return() function. Otherwise, try error handling facilities:

full <- function() {
   message("before")
   small <- function(x){
      if (x<3) {
         # or just e.g. return(NULL)
         stop("smaller than 3")
      }
      print(x)
   }

   tryCatch({   
      small(2)
   }, error=function(err) {
      # do nothing on error
   })
   message("after") 
}

full()
## before
## after

Upvotes: 4

Related Questions