4

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 ?

3
  • You don't need to explicitly specify the return in R. It will return the last line Commented Jun 6, 2020 at 17:59
  • Never used returnValue, but return and no return are one and the same Commented Jun 6, 2020 at 18:03
  • when i used returnValue it worked as same as return and no return, so when to go for returnValue.? Commented Jun 6, 2020 at 18:20

2 Answers 2

5
  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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.