Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function return in R programming language

Tags:

r

I need help on returning a value/object from function

noReturnKeyword <- function(){
  'noReturnKeyword'
}

justReturnValue <- function(){
  returnValue('returnValue')
}

justReturn <- function(){
  return('justReturn')
}

When I invoked these functions: noReturnKeyword(), justReturnValue(), justReturn(), I got output as [1] "noReturnKeyword", [1] "returnValue", [1] "justReturn" respectively.

My question is, even though I have not used returnValue or return keywords explicitly in noReturnKeyword() I got the output (I mean the value returned by the function).

So what is the difference in these function noReturnKeyword(), justReturnValue(), justReturn()

What is the difference in these words returnValue('') , return('')? are these one and the same?

When to go for returnValue('') and return('') in R functions ?

like image 433
user2587669 Avatar asked Nov 16 '25 03:11

user2587669


2 Answers

  1. return is the explicite way to exit a function and set the value that shall be returned. The advantage is that you can use it anywhere in your function.

  2. If there is no explicit return statement R will return the value of the last evaluated expression

  3. returnValueis only defined in a debugging context. The manual states:

the experimental returnValue() function may be called to obtain the value about to be returned by the function. Calling this function in other circumstances will give undefined results.

In other words, you shouldn't use that except in the context of on.exit. It does not even work when you try this.

justReturnValue <- function(){
  returnValue('returnValue')
  2
}

This function will return 2, not "returnValue". What happened in your example is nothing more than the second approach. R evaluates the last statement which is returnValue() and returns exactly that.

If you use solution 1 or 2 is up to you. I personally prefer the explicit way because I believe it makes the code clearer. But that is more a matter of opinion.

like image 113
Jan Avatar answered Nov 17 '25 17:11

Jan


In R, according to ?return

If the end of a function is reached without calling return, the value of the last evaluated expression is returned.

like image 37
akrun Avatar answered Nov 17 '25 16:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!