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:
Syntax
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
square_explicit <- function(n) {
return(n * n)
}
square_implicit <- function(n) {
n * n
}
cat(square_explicit(5), square_implicit(5), "\n")
Login to try C/C++/Java/PHP code in the editor
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
- Putting code after
return()in the function, which never runs. - Relying on the last expression when it is an assignment such as
y <- n * n, which returns the value invisibly, so nothing prints. - Returning several values with
return(a, b), which is an error; return a list likelist(a = a, b = b).
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: