9.5 reduce() family

The reduce() function is a powerful functional that allows you to abstract away from a sequence of functions that are applied in a fixed direction.

reduce() takes a vector as its first argument, a function as its second argument, and an optional .init argument last. It will then apply the function repeatedly to the vector until there is only a single element left.

(Hint: start at the top of the image and read down.)

Let me really quickly demonstrate reduce() in action.

Say you wanted to add up the numbers 1 through 5 using only the plus operator +. You could do something like:

1 + 2 + 3 + 4 + 5
#> [1] 15

Which is the same as:

reduce(1:5, `+`)
#> [1] 15

And if you want the start value to be something that is not the first argument of the vector, pass that value to the .init argument:


identical(
  0.5 + 1 + 2 + 3 + 4 + 5,
  reduce(1:5, `+`, .init = 0.5)
)
#> [1] TRUE