Multiple Return Values in R Programming Language

R supports multiple return values through the use of lists. This feature is often used to return both result and error values from a function.

# The list() in this function signature shows that
# the function returns multiple values.
vals <- function() {
  return(list(3, 7))
}

# In the main function, we demonstrate how to use 
# multiple return values
main <- function() {
  # Here we use the multiple return values from the
  # call with list unpacking.
  result <- vals()
  a <- result[[1]]
  b <- result[[2]]
  print(a)
  print(b)
  
  # If you only want a subset of the returned values,
  # you can use list indexing.
  c <- vals()[[2]]
  print(c)
}

# Run the main function
main()

To run the program, save it as multiple_return_values.R and use Rscript:

$ Rscript multiple_return_values.R
[1] 3
[1] 7
[1] 7

In R, functions can return multiple values using lists. While not a built-in language feature like in some other languages, this approach provides similar functionality. The vals() function returns a list containing two integers.

In the main() function, we demonstrate two ways of working with these multiple return values:

  1. We can unpack the list into separate variables a and b.
  2. We can also access specific elements of the returned list using indexing, as shown with c.

This pattern is commonly used in R for functions that need to return multiple pieces of data, such as statistical functions that return both a result and associated metadata.

R’s flexibility with lists and its functional programming features make it well-suited for handling multiple return values in a clean and readable manner.