[R] Why 'return' is needed in R?

Duncan Murdoch murdoch at stats.uwo.ca
Tue Oct 27 15:22:18 CET 2009


On 10/27/2009 10:12 AM, Peng Yu wrote:
> It seems that 'return' is not necessary when returning a value. If
> this is the case, I don't understand why 'return' is a keyword in R.
> Is there a case in which I have to use 'return'?

If you want to return early from a function you need it, e.g.

f <- function(x) {
   if (x < 10) return(x^2)
   x <- x + 1
   x
}

Often these can be rewritten without the explicit return(), but they can 
be less clear.  For example, the above is equivalent to

f <- function(x) {
   if (x < 10) x^2
   else {
     x <- x + 1
     x
   }
}

but here it is not obvious that the x^2 is really the value of the last 
statement in the function.

Duncan Murdoch

> 
>> f<-function(x) {
> +   x
> + }
>> g<-function(x) {
> +   return(x)
> + }
>> print(f(2))
> [1] 2
>> print(g(2))
> [1] 2
>>
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list