Menu
Coddy logo textTech

Return Values

Part of the Fundamentals section of Coddy's R journey — lesson 48 of 78.

So far, our functions have printed output directly. But often you want a function to compute a value and send it back so you can use it elsewhere in your code. This is where return values come in.

Use the return() function to send a value back from your function:

add <- function(a, b) {
  return(a + b)
}

result <- add(5, 3)
print(result)

Output:

[1] 8

Instead of printing inside the function, we return the sum. The returned value can then be stored in a variable, used in calculations, or passed to other functions.

This makes functions much more versatile:

double <- function(x) {
  return(x * 2)
}

print(double(5) + double(3))

Output:

[1] 16

In R, if you don't use return(), the function automatically returns the last evaluated expression. However, using return() explicitly makes your code clearer and is especially useful when you want to exit a function early.

challenge icon

Challenge

Easy

Create a function called calculate_power that takes two arguments: base and exponent. The function should return the result of raising the base to the power of the exponent (using the ^ operator).

Read two numbers from input, convert them to numeric values, and call your function. Store the returned value in a variable called result, then print result.

For example, if the inputs are 2 and 3, the output should be:

[1] 8

If the inputs are 5 and 2, the output should be:

[1] 25

Cheat sheet

Functions can send values back using the return() function. This allows you to store the result in a variable or use it in other operations:

add <- function(a, b) {
  return(a + b)
}

result <- add(5, 3)
print(result)  # [1] 8

Returned values can be used directly in expressions:

double <- function(x) {
  return(x * 2)
}

print(double(5) + double(3))  # [1] 16

In R, functions automatically return the last evaluated expression if return() is not used. However, using return() explicitly makes code clearer and allows early exits from functions.

Try it yourself

# Read input
con <- file("stdin", "r")
base <- as.numeric(suppressWarnings(readLines(con, n = 1)))
exponent <- as.numeric(suppressWarnings(readLines(con, n = 1)))

# TODO: Create a function called calculate_power that takes base and exponent
# and returns base raised to the power of exponent using the ^ operator


# TODO: Call your function with the input values and store the result in 'result'


# Output the result
print(result)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals