← Back to R Course | Chapter 5: Functions | Lesson 4 of 7

Return Values

A return value is the answer a function hands back, like a vending machine dropping your snack. If you do not say what to return, R gives back the last thing it worked out.

In this page:

  1. Return Values
Syntax
r
function_name <- function(arg) {
  # body
  return(value)
}

Return Values

A function's value is either whatever return() explicitly returns, or -- if return() is never called -- the value of its last evaluated expression.

Because of this implicit return behavior, many short R functions omit return() entirely. Both styles are common and idiomatic depending on the function's complexity.

Note: For simple one-expression functions, R idiom often skips return() and just lets the last expression's value be returned implicitly.

Example: Return Values

markup
square_explicit <- function(n) {
  return(n * n)
}

square_implicit <- function(n) {
  n * n
}

cat(square_explicit(5), square_implicit(5), "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting code after return() in the function, which never runs.
  2. Relying on the last expression when it is an assignment such as y <- n * n, which returns the value invisibly, so nothing prints.
  3. Returning several values with return(a, b), which is an error; return a list like list(a = a, b = b).
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.