๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Returning Values

return() hands a value back to the caller and ends the function call at once.

An early return

This function returns adult when the age reaches 18. A younger age returns minor instead.

check_age <- function(age) {
  if (age >= 18) {
    return("adult")
  }
  return("minor")
}
print(check_age(20))
print(check_age(12))

Two styles, one answer

One function gives back its last value and the other uses return. Both calls with 5 give back 25.

square_a <- function(num) {
  num * num
}
square_b <- function(num) {
  return(num * num)
}
print(square_a(5))
print(square_b(5))

Storing a returned value

The call gives back half of 10. The returned value is stored in result and then printed.

half <- function(num) {
  return(num / 2)
}
result <- half(10)
print(result)

Example

square <- function(num) {
  return(num * num)
}
print(square(3) + 1)

Key points

  • return() gives its value to the caller as the result of the call.
  • The call ends as soon as return() runs.
  • Lines after a return() that runs do not run in that call.
  • A block can also give back its last value with no return() at all.
  • The two styles can give back the same result.
  • A returned value can sit inside a bigger expression.

In this example, square gives back 9 for the input 3. The returned 9 is then used inside the bigger expression and 1 is added before printing.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does return() do when it runs inside a function?