Lesson 10 of 16
Higher-Order Functions
Functions as Values
In R, functions are first-class objects. You can pass them as arguments, return them from other functions, and store them in variables.
Passing Functions
apply_twice <- function(f, x) {
f(f(x))
}
double <- function(x) x * 2
cat(apply_twice(double, 3), "\n") # 12
Anonymous Functions
You can create functions inline without naming them:
result <- sapply(1:5, function(x) x ^ 2)
cat(result, "\n") # 1 4 9 16 25
R 4.1+ also supports a shorthand syntax with \():
result <- sapply(1:5, \(x) x ^ 2)
Closures
Functions in R capture their enclosing environment:
make_adder <- function(n) {
function(x) x + n
}
add5 <- make_adder(5)
cat(add5(3), "\n") # 8
cat(add5(10), "\n") # 15
The inner function remembers the value of n from when make_adder was called.
Your Task
Write a function make_multiplier that takes a number n and returns a function that multiplies its argument by n. Use it to create triple (multiplies by 3) and print triple(4) and triple(7).
R runtime loading...
Loading...
Click "Run" to execute your code.