reduce(), accumulate(), and walk()
Fold lists, build cumulative results, and apply side-effects with walk().
Beyond map() — Other purrr Verbs
While map() applies a function independently to each element, some tasks require operations that combine elements (reduce), accumulate intermediate results, or apply functions purely for side effects (walk). purrr provides dedicated functions for each case.
library(purrr)
# Example: combining a list of numbers into a single value
nums <- list(1, 2, 3, 4, 5)
# We want: 1 + 2 + 3 + 4 + 5 = 15
# map() can't do this — it returns 5 separate results
# reduce() folds the list into one value
result <- reduce(nums, `+`)
cat('Sum via reduce:', result)reduce() — Fold a List to One Value
reduce(.x, .f, .init) applies .f cumulatively to elements of .x, from left to right, reducing the list to a single value. reduce(list(a,b,c), f) computes f(f(a,b),c).
library(purrr)
# reduce with max: find the overall maximum
values <- list(42, 17, 89, 55, 23)
result <- reduce(values, max)
cat('Maximum:', result, '\n')
# reduce with paste: concatenate strings
words <- list('The', 'quick', 'brown', 'fox')
reduce(words, paste)All lessons in this course
- map() and Typed Variants
- map2() and pmap() for Multiple Inputs
- reduce(), accumulate(), and walk()
- keep(), discard(), and List Filtering