How to Return Value from Function in R (With Examples)


You can use the following methods to return one or more values from a function in R:

Method 1: Return One Value

my_function <- function(A, B) {
  C <- A * B
  return(C)
}

Method 2: Return Multiple Values

my_function <- function(A, B) {
  C <- A * B
  D <- A + B
  E <- A - B
  return(list(C, D, E))
}

The following examples show how to use each method in practice.

Example 1: Return One Value from Function in R

The following code shows how to create a function that returns one value:

#define function that returns one value
multiply_values <- function(A, B) {
  C <- A * B
  return(C)
}

#use function
multiply_values(10, 3)

[1] 30

Notice that the function returns one value: the product of 10 and 3.

Example 2: Return Multiple Values from Function in R

The following code shows how to create a function that returns multiple values:

math_stuff <- function(A, B) {
  C <- A * B
  D <- A + B
  E <- A - B
  return(list(C, D, E))
}

#use function
math_stuff(10, 3)

[[1]]
[1] 30

[[2]]
[1] 13

[[3]]
[1] 7

The function returns three values:

  • The first value is 10 * 3 = 30
  • The second value is 10 + 3 = 13
  • The third value is 10 – 3 = 7

Note: In this particular example, we returned three values but you can use similar syntax to return as many values as you’d like using the return() argument.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Create a Nested For Loop in R
How to Loop Through Column Names in R
How to Append Values to a Vector Using a Loop in R

Leave a Reply

Your email address will not be published.