Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, what is the keyword for jumping out of a function without executing the rest of it?

Tags:

function

return

r

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.

like image 429
Causality Avatar asked Jun 08 '11 19:06

Causality


2 Answers

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> 
like image 164
Dirk Eddelbuettel Avatar answered Nov 15 '22 16:11

Dirk Eddelbuettel


I think what you're looking for is:

stopifnot()
like image 35
Brandon Bertelsen Avatar answered Nov 15 '22 17:11

Brandon Bertelsen