Passing Functions
Part of the Logic & Flow section of Coddy's R journey. Lesson 28 of 64.
A function can take another function as an argument and call it. apply_twice() below works with any function of one argument:
apply_twice <- function(f, x) f(f(x))
print(apply_twice(\(x) x + 3, 10))
print(apply_twice(toupper, "ok"))Output:
[1] 16
[1] "OK"Built-in functions such as sum, max or toupper are values too, so pass them by name without parentheses. With parentheses they would be called instead:
summarize <- function(xs, how) how(xs)
print(summarize(c(4, 9, 2), max))
print(summarize(c(4, 9, 2), sum))Output:
[1] 9
[1] 15A function that takes a predicate, a function returning TRUE or FALSE, can count or select values by any rule:
count_if <- function(xs, keep) {
n <- 0
for (x in xs) if (keep(x)) n <- n + 1
n
}
print(count_if(c(3, 8, 10, 5), \(x) x %% 2 == 0))
print(count_if(c(3, 8, 10, 5), \(x) x > 4))Output:
[1] 2
[1] 3The caller decides the behaviour and the function supplies the loop, so one function covers many cases:
transform_each <- function(xs, f) {
out <- c()
for (x in xs) out <- c(out, f(x))
out
}
print(transform_each(1:4, \(x) x * 10))
print(transform_each(c("a", "b"), toupper))Output:
[1] 10 20 30 40
[1] "A" "B"Challenge
EasyComplete apply_n(f, x, n). Call f on x, then on the result, n times in total, and return the final value. When n is 0, return x unchanged.
The supplied code defines three functions, double, inc and half. It reads the name of one of them, the start value and n, and prints the result of apply_n().
Try it yourself
apply_n <- function(f, x, n) {
# Write your code here
x
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
ops <- list(double = \(x) x * 2, inc = \(x) x + 1, half = \(x) x / 2)
cat(apply_n(ops[[input[1]]], as.numeric(input[2]), as.numeric(input[3])), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler