Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

A while back I got rebuked by Simon Urbanek from the R core team (I believe) for recommending a user to explicitly calling return at the end of a function (his comment was deleted though):

foo = function() {

  return(value)

}

instead, he recommended:

foo = function() {

  value

}

Probably in a situation like this it is required:

foo = function() {

 if(a) {

   return(a)

 } else {

   return(b)

 }

}

His comment shed some light on why not calling return unless strictly needed is a good thing, but this was deleted.

My question is: Why is not calling return faster or better, and thus preferable?

1 Answer

0 votes
by

According to the man page of the function in R:

function( arglist ) expr

return(value)

Return is a primitive function that is used to clearly describe the leaves of a code where, the routine should end, jump out of the function and return a value.

  •  There is no danger in using return, and it comes down to the strategy and programming style of the programmer whether or not to use it. The return function when used with the last value as an argument needs one extra call than not using a return. Simple measurement, however, shows that the resulting difference is very small and thus can not be the reason for not using explicit return.
  •  According to Hadley Wickham-Chief Scientist at RStudio Tthe speed of return is really the last thing you should be worrying about.
  •  Core R programmers use both of these approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions. 
  • The return() is often used without arguments returning NULL in cases to conditionally stop the function. It can’t be said if it is better or not as a standard user or analyst using R cannot see the real difference.

Examples:

(function() {1;2;3;4})() #without return()

[1] 4

(function() {1;2;3;4;return(10)})() #with return value

[1] 10

(function() {1;2;return();3;4})() #return used to stop the flow

NULL

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...