0
0
R-programmingHow-ToBeginner · 3 min read

How to Return Value from Function r in R: Simple Guide

In R, you return a value from a function by placing the value as the last expression or using the return() function inside the function body. The last evaluated expression is automatically returned if return() is not used.
📐

Syntax

In R, a function returns a value by evaluating the last expression or explicitly using return(). The general syntax is:

  • function_name <- function(arguments) {
  • # code
  • return(value) (optional)
  • }

If return() is omitted, the last expression's result is returned automatically.

r
my_function <- function(x) {
  y <- x + 1
  return(y)  # explicitly returns y
}

my_function2 <- function(x) {
  y <- x + 1
  y  # last expression returned automatically
}
💻

Example

This example shows two functions that add 1 to the input and return the result. One uses return(), the other relies on the last expression.

r
add_one_return <- function(num) {
  result <- num + 1
  return(result)
}

add_one_last <- function(num) {
  result <- num + 1
  result
}

print(add_one_return(5))
print(add_one_last(5))
Output
[1] 6 [1] 6
⚠️

Common Pitfalls

Beginners often forget that only the last expression is returned if return() is not used. Placing code after return() will not run. Also, forgetting to include a value to return results in NULL.

r
wrong_function <- function(x) {
  return(x + 1)
  x + 2  # This line is ignored
}

correct_function <- function(x) {
  y <- x + 1
  y  # returned automatically
}
📊

Quick Reference

ConceptDescription
Implicit returnLast expression in function is returned automatically
Explicit returnUse return(value) to return early or clearly
Code after returnIgnored, never executed
No return valueFunction returns NULL by default

Key Takeaways

The last expression in an R function is returned automatically if return() is not used.
Use return(value) to explicitly return a value or exit a function early.
Code after a return() call will not run, so place return() carefully.
If no value is returned, the function returns NULL by default.
Returning values correctly helps your functions communicate results clearly.