Week 7: Writing Reusable Code with Functions
Learn how to define and use functions to make your R code modular and efficient.
Explore Chapter 7Returning Values from Functions.
Functions often need to compute a result and send it back to the part of the script that called it. R handles return values in a specific way.
Implicit Return
By default, an R function implicitly returns the value of the last expression evaluated within its body.
add_numbers <- function(x, y) {
sum_result <- x + y
sum_result # This is the last evaluated expression, so its value is returned
}
result <- add_numbers(10, 5)
print(result) # Output: [1] 15
Explicit Return with `return()`
You can also use the `return()` function to explicitly specify the value to return and potentially exit the function early (e.g., based on a condition).
check_value <- function(x) {
if (x <= 0) {
return("Value must be positive") # Exit early and return message
}
# This code only runs if x > 0
processed_value <- sqrt(x)
return(processed_value) # Explicitly return the calculated value
}
output1 <- check_value(9)
print(output1) # Output: [1] 3
output2 <- check_value(-5)
print(output2) # Output: [1] "Value must be positive"
Returning Multiple Values (as a List)
To return multiple values, you typically combine them into a list (often a named list for clarity).
calculate_stats <- function(numbers) {
mean_val <- mean(numbers)
sd_val <- sd(numbers)
return(list(mean = mean_val, stdev = sd_val))
}
data <- 1:10
stats_result <- calculate_stats(data)
print(stats_result)
# Output:
# $mean
# [1] 5.5
# $stdev
# [1] 3.02765
# Access individual returned values
print(stats_result$mean) # Output: [1] 5.5