R Functions
A function is a named, reusable piece of code. You have already used many built-in functions such as mean(), paste() and round(). Now you will write your own with the function keyword.
say_hello <- function() {
cat("Hello from a function!\n")
}
say_hello()
say_hello()Hello from a function!
Hello from a function!
A function is a value like any other: function() { ... } creates it and <- gives it a name. Call it by writing the name followed by parentheses.
Arguments
Values passed into a function are called arguments. Inside the function they act like local variables:
bmi <- function(weight_kg, height_m) {
weight_kg / height_m^2
}
bmi(70, 1.75)
bmi(height_m = 1.6, weight_kg = 55) # named: order doesn't matter[1] 22.85714
[1] 21.48437
R matches arguments by name first, then by position. Naming arguments makes calls clearer, especially when a function has many of them.
Return values
A function returns the value of its last expression. Use return() to leave early:
safe_divide <- function(a, b) {
if (b == 0) {
return(NA)
}
a / b
}
safe_divide(10, 4)
safe_divide(1, 0)[1] 2.5
[1] NA
To return several values, put them in a list (or a named vector):
describe <- function(x) {
list(n = length(x), mean = mean(x), sd = round(sd(x), 3))
}
stats <- describe(c(4, 8, 15, 16, 23, 42))
stats$mean
stats$sd[1] 18
[1] 13.491
Default values
Give an argument a default with = in the definition. Callers may then leave it out:
greet <- function(name, greeting = "Hello", punct = "!") {
paste0(greeting, ", ", name, punct)
}
greet("Mia")
greet("Leo", greeting = "Welcome")
greet("Zoe", punct = "?")[1] "Hello, Mia!"
[1] "Welcome, Leo!"
[1] "Hello, Zoe?"
Variable number of arguments: ...
The special argument ... collects any extra arguments. It is often passed on to another function:
shout <- function(...) {
words <- c(...)
toupper(paste(words, collapse = " "))
}
shout("r", "is", "fun")
my_mean <- function(x, ...) {
round(mean(x, ...), 1)
}
my_mean(c(2, 4, NA, 9), na.rm = TRUE)[1] "R IS FUN"
[1] 5
Vectorised functions for free
Because arithmetic in R is vectorised, a function written for one number usually works on a whole vector too:
to_fahrenheit <- function(celsius) celsius * 9 / 5 + 32
to_fahrenheit(c(-10, 0, 37, 100))[1] 14.0 32.0 98.6 212.0
Anonymous functions
A function doesn't need a name. Short anonymous functions are common as arguments to other functions. R 4.1 added the shorthand \(x) for function(x):
sapply(1:5, function(n) n^2)
sapply(1:5, \(n) n^2 + 1)
(\(x, y) x * y)(6, 7)[1] 1 4 9 16 25
[1] 2 5 10 17 26
[1] 42
Test yourself
What does a function return if there is no return() call?
- NULL
- The value of the last evaluated expression
- TRUE
- Nothing; it's an error
Given f <- function(a, b = 2) a * b, what is f(5)?
- 5
- 7
- 10
- An error
What does \(x) x + 1 create?
- A string
- An anonymous function
- A regular expression
- A formula