How to cleanly exit a function when condition not met

Sorry if this is a totally obvious question...

I want to cleanly exit a function when a condition is not met, bypassing more code that comes after.
break and next aren't relevant as it is a function, while reading on stackoverflow both stop() and exit() are recommended but the first throws an error and the second is a function that doesn't seem to exist.
For example:

test = function(x) {

    if (x > 1) {
        print("cool")
    } else if (x == 1) {
        stop("not cool")
    }
    
    x = x*2
    return(x*5)
}

> test(1)
Error in test(1) : not cool
Called from: test(1)
Browse[1]> 

This is not my actual function but an analog. I think I could configure things to use stopifnot() but there has to be some other way to cleanly do this I'm missing?
Thanks :smiley_cat:

I think the question to you is what do you want the function to return instead of an error? In this version, I have it return NA. You could choose NULL as an alternative. The code that uses the returned value would have to handle the NA or NULL appropriately.

test = function(x) {
  
  if (x > 1) {
    print("cool")
  } else if (x == 1) {
    #stop("not cool")
    return(NA)
  }
  
  x = x*2
  return(x*5)
}
test(0)
#> [1] 0
test(1)
#> [1] NA
test(2)
#> [1] "cool"
#> [1] 20

Created on 2022-06-22 by the reprex package (v2.0.1)

1 Like

There we go ... the nice simple solution I was overlooking :smiley: Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.