R Return Value from Function

In this article, you will learn to return a value from a function in R. You'll also learn to use functions without the return function.

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


Syntax of return()

The syntax of the return() function is:

return(expression)

Here, expression is evaluated, and its value is stored as the result of the function.

The value specified in the return() statement is passed as the output of the function.


Example of 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)
}

check(1)
check(-10)
check(0)

Output

[1] "Positive"
[1] "Negative"
[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 the 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) 
}
# call function multi_return() and assign the result to variable a
a <- multi_return()
a$color
a$size
a$shape

Output

[1] "red"
[1] 20
[1]"round"

Here, the function multi_return() creates a list object my_list, assigns some values to its elements, and then returns the entire list as the output of the function.

The list contains three elements: "color" with the value "red", "size" with the value 20, and "shape" with the value "round".

The multi_return() function is called and its result is assigned to the variable a.

Here,

  • a$color - accesses the value of the "color" element
  • a$size - accesses the value of the "size" element
  • a$shape - accesses the value of the "shape" element

Check out these examples to learn more:

Did you find this article helpful?