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] 8Instead 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] 16In 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
EasyCreate 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] 8If the inputs are 5 and 2, the output should be:
[1] 25Cheat 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] 8Returned values can be used directly in expressions:
double <- function(x) {
return(x * 2)
}
print(double(5) + double(3)) # [1] 16In 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)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values