Functions
Prerequisites: Loops
A function is a named, reusable block of code that performs a task.
You've already used many: mean, paste, round. Now you'll write
your own.
Real-world analogy: a function is a recipe. You write the steps once, then just say "make pancakes" whenever you want them.
Syntax
name <- function(argument1, argument2 = default) {
# code
result # the last value is returned
}
Example
celsius_to_fahrenheit <- function(celsius) {
celsius * 9 / 5 + 32
}
celsius_to_fahrenheit(25)
celsius_to_fahrenheit(c(0, 37, 100))
Expected output
[1] 77
[1] 32.0 98.6 212.0
function(celsius)creates a function with one argument.- The last expression is the function's result — no
returnneeded. - Because the body uses vectorized arithmetic, the function automatically works on whole vectors too.
Default arguments and named calls
greet <- function(name, greeting = "Hello") {
paste0(greeting, ", ", name, "!")
}
greet("Ada")
greet("Ada", greeting = "Welcome")
greet(greeting = "Hi", name = "Linus")
[1] "Hello, Ada!"
[1] "Welcome, Ada!"
[1] "Hi, Linus!"
return() for early exits
return() exits immediately — handy for checking inputs first:
safe_divide <- function(a, b) {
if (b == 0) {
return(NA)
}
a / b
}
safe_divide(10, 2)
safe_divide(10, 0)
[1] 5
[1] NA
Common mistakes
- Ending a function with
cat()orprint()instead of returning a value. Return values from functions, and print them where you call the function. - Forgetting to call the function with parentheses: typing
greetprints the function's code instead of running it.
Practice
Write bmi(weight_kg, height_m) that returns the body-mass index
(weight / height^2) rounded to one decimal. Test it with 70 kg and
1.75 m.
Show solution
bmi <- function(weight_kg, height_m) {
round(weight_kg / height_m^2, 1)
}
bmi(70, 1.75)
[1] 22.9