I am wondering if there is any keyword in R for jumping out of a function without executing the rest of it. In C, Java, or Matlab, there is the keyword 'return'. But the 'return' keyword in R works different than in those languages. Here is an example,
myfunc = function() {
if (TRUE) {
return # hopefully, jump out of the function
}
print('the rest of the function is still executed!')
}
In the example, languages like Java will not execute 'the rest' when 'return' is met, while in R 'return' is only in the scope of the if statement and the rest of the functions is still executed. In this particular example I could have added an 'else' block to achieve it but I would like to know if there is any keyword which would give similar behaviors as in Java etc. Thanks.
What you show is actually syntactically valid R code ... but you have the mistake of not supplying a value to return
. So here is a corrected version:
R> myfunc <- function() {
if (TRUE) {
return(NULL) # hopefully, jump out of the function
}
print('the rest of the function is still executed!')
}
myfunc <- function() {
+ if (TRUE) {
+ return(NULL) # hopefully, jump out of the function
+ }
+ print('the rest of the function is still executed!')
+ }
R> myfunc()
NULL
R>
I think what you're looking for is:
stopifnot()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With