Return in R - r - learn r - r programming
- Many times, we require our functions to do some processing and return back the result.
- This is done with the return() function in R.
- In other words transmit a value back to the caller by explicitly calling return().
- Without this call, the value of the last executed statement will be returned by default.
- The value returned from a function can be any valid object.
- Here is an example which will return whether a given number is positive, negative or zero.
Here, given sample codes.
Functions without return()
- If there are no explicit returns from a function, the value of the last evaluated expression is returned automatically in R.
- For example, the following is equivalent to the above function.
- We generally use explicit return() functions to return a value immediately from a function.
- If it is not the last statement of the function, it will prematurely end the function bringing the control to the place from which it was called.
- In the above example, if x > 0, the function immediately returns "Positive" without evaluating rest of the body.
- The return() function can return only a single object. If we want to return multiple values in R, we can use a list (or other objects) and return it.
- Following is an example.
- Here, we create a list my_list with multiple elements and return this single list.