[1] 17
2026-02-03
Functionals are functions that take a function as input and return a (vector of) number(s) as output:
in base: e.g. uniroot, integrate, …
in tidyverse: e.g. summarize, mutate, …
another example: purrr::map applies a function on every element in a list

apply_to(d,f) in R that applies the function f to every variable of data set d.Run the statement mtcars |> apply_to(class)
Create a statement that returns the number of missing values in each of the variables of txhousing (in the ggplot2 package)
How do your results differ from corresponding calls to sapply?
Map and variantsmap applies a function to every item in a list
map_XXX additionally formats output as XXX: can be chr (character), dbl (numeric), lgl (logical), …
walk does not have any output, i.e. operates through side effects (e.g. print message, create files, …)
map2 and pmap take two/arbitrarily many lists as input
map functions serve as iterators, i.e. replace (most) loops
map works within the tidyverse specs: apply either globally to each variable or within mutate to each element in a (set of) variable(s)
map doesn’t need to preserve the order in the variable, i.e. signal to processor that code could be run in parallel or distributed (e.g. good for large data)
reduce takes a function f and a vector x and applies the function repeatedly to its output f(f(f( ... f(x))))
reduce is conceptually a recursive approach
a function that produces another function
often a shift in perspective (re-express as function of another parameter, e.g. likelihood vs density)
transformations (box-cox, scales in ggplot2)
Better (because any terms in x are only evaluated once)
ggplot() +
geom_function(fun = ll_poisson(rpois(10, lambda)), xlim = c(0, 5)) +
geom_function(fun = ll_poisson(rpois(10, lambda)), xlim = c(0, 5)) +
geom_function(fun = ll_poisson(rpois(10, lambda)), xlim = c(0, 5)) +
geom_function(fun = ll_poisson(rpois(20, lambda)), xlim = c(0, 5)) +
geom_function(fun = ll_poisson(rpois(20, lambda)), xlim = c(0, 5)) +
geom_function(fun = ll_poisson(rpois(20, lambda)), xlim = c(0, 5)) Re-write the previous expression with an approach that avoids the duplication of lines
No peeking!
geom_function_sample <- function(fun, sample, args) {
function(n, samples, ...) {
args = append(args, c("n"=n))
1:samples |> purrr::map(
.f = function(i) {
geom_function(fun = fun(do.call(sample, args=args)), ...)
})
}
}
add_function_layer <- geom_function_sample(
fun = ll_poisson, sample=rpois,
args = list(lambda=lambda))