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

Sarah Goslee sarah.goslee at gmail.com
Tue Oct 27 15:21:28 CET 2009


Did you read the help?

If you use return(), that value is returned regardless of where in the function
it appears. This can be used in conditionals, for example.

If the function never hits a return value, the value of the last
evaluated expression
is returned.

testfunction <- function(x, controlvar="a")
{
  if(controlvar != "a") {
    return(x^2)
  }

  x + 1

}

> testfunction(4, "a")
[1] 5
> testfunction(4, "b")
[1] 16


Sarah


On Tue, Oct 27, 2009 at 10:12 AM, Peng Yu <pengyu.ut at gmail.com> 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'?
>
>> f<-function(x) {
> +   x
> + }
>> g<-function(x) {
> +   return(x)
> + }
>> print(f(2))
> [1] 2
>> print(g(2))
> [1] 2
>>

-- 
Sarah Goslee
http://www.functionaldiversity.org




More information about the R-help mailing list