Functions in R: how to get your output

Tim Oltman
2 min readMar 26, 2022
Photo by Erda Estremera on Unsplash

Once you begin using functions in R you will need to know a few things about returning values from functions. This article will cover how to return values, and how to return multiple values or objects from a function.

Return values

First of all, R will by default return the value from the last line of code in your function.

my_func <- function(x) {
y <- x + 2
y
}

In this case, my_func will return the value of y.

> my_func(2)
[1] 4

You can also use the return function to immediately return a value and end the function execution. This might be necessary if your function has branching control. For example, consider the following function:

greater_than <- function(x, y) {
if(x > y) {
return("yes")
}
return("no")
}

The function greater_than will return the string "yes" immediately if x > y evaluates to TRUE. Otherwise, the if-statement will finish and "no" will be returned.

It can be good practice to use a return function even in the last line of a function and no other return functions are used. Always strive to make your code as readable as possible.

How to return multiple values

Sometimes you will want to return multiple values from a function. But you can only return a single object from a function. The solution is to return an object like a vector or a list that contains all of the values you need.

my_list_func <- function() {
return(list(a = 1, b = "two"))
}

This function returns a list with two elements.

> new_list <- my_list_func()
> new_list
$a
[1] 1
$b
[1] "two"

The elements of the list can be accessed by new_list$a and new_list$b. You can then use them as in the following code.

> new_list$a
[1] 1
> new_list$b
[1] "two"

I hope that helps you return exactly what you need from your functions in R.

--

--

Tim Oltman

Data Nerd, Information Visualizer, Social Scientist