R Return Value from Function

Many a times, we will require our functions to do some processing and return back the result. This is accomplished with the return() function in R.


Syntax of return()

return(expression)

The value returned from a function can be any valid object.


Example: return()

Let us look at an example which will return whether a given number is positive, negative or zero.

check <- function(x) {
   if (x > 0) {
       result <- "Positive"
   }
   else if (x < 0) {
       result <- "Negative"
   }
   else {
       result <- "Zero"
   }
   return(result)
}

Here, are some sample runs.

> check(1)
[1] "Positive"

> check(-10)
[1] "Negative"

> check(0)
[1] "Zero"

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.

check <- function(x) {
   if (x > 0) {
       result <- "Positive"
   }
   else if (x < 0) {
       result <- "Negative"
   }
   else {
       result <- "Zero"
   }
   result
}

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.

check <- function(x) {
   if (x>0) {
       return("Positive")
   }
   else if (x<0) {
       return("Negative")
   }
   else {
       return("Zero")
   }
}

In the above example, if x > 0, the function immediately returns "Positive" without evaluating rest of the body.


Multiple Returns

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.

multi_return <- function() {
   my_list <- list("color" = "red", "size" = 20, "shape" = "round")
   return(my_list) 
}

Here, we create a list my_list with multiple elements and return this single list.

> a <- multi_return()
> a$color
[1] "red"

> a$size
[1] 20

> a$shape
[1] "round"
Did you find this article helpful?