Reduce
Reduce takes a binary function and a vector or list, then applies the function cumulatively: given [a, b, c] and binary function f, it computes f(f(a, b), c). The result is a single value.
Signature
Reduce(f, x, init, right = FALSE, accumulate = FALSE)
Parameters:
f— a binary function (takes exactly two arguments)x— a vector or list to reduceinit— optional initial value for the accumulatorright— ifTRUE, fold right-to-left instead of left-to-rightaccumulate— ifTRUE, return all intermediate results instead of just the final one
Basic Usage
Sum and Product
Reduce(`+`, c(1, 2, 3, 4, 5))
# [1] 15
Reduce(`*`, c(1, 2, 3, 4, 5))
# [1] 120
Set Intersection
Reduce(intersect, list(c("a", "b", "c"), c("b", "c", "d"), c("c", "d", "e")))
# [1] "c"
Initial Value
Pass init to set a starting value for the reduction:
Reduce(`+`, c(1, 2, 3), init = 10)
# [1] 16
Reduce(`+`, c(), init = 10)
# [1] 10
Without init, an empty vector causes an error. With init, empty vectors return the initial value safely.
Right Folding
Set right = TRUE to fold from right to left:
Reduce(`-`, c(10, 3, 2))
# [1] 5
Reduce(`-`, c(10, 3, 2), right = TRUE)
# [1] 9
Left fold: ((10 - 3) - 2) = 5
Right fold: 10 - (3 - 2) = 9
Accumulate Mode
Set accumulate = TRUE to return all intermediate results:
Reduce(`+`, c(1, 2, 3, 4, 5), accumulate = TRUE)
# [1] 1 3 6 10 15
Useful when you need running totals or intermediate states:
# Running minimum
Reduce(pmin, c(5, 3, 4, 1, 2), accumulate = TRUE)
# [1] 5 3 3 1 1
Building Complex Objects
Reduce composes operations where later steps depend on earlier results:
# Build a configuration list from partial pieces
configs <- list(
list(theme = "light"),
list(font = "Arial"),
list(size = 14)
)
combined <- Reduce(function(cfg, new) c(cfg, new), configs, init = list())
# [[1]]$theme [1] "light"
# [[2]]$font [1] "Arial"
# [[3]]$size [1] 14
Common Pitfalls
Function Must Be Binary
Reduce passes exactly two arguments at a time:
Reduce(function(x) x^2, c(1, 2, 3))
# Error: evaluation nested too deeply
Wrap unary functions to adapt them:
Reduce(function(a, b) a + b^2, c(1, 2, 3))
# [1] 32
Mistaking Accumulated Value
With accumulate = TRUE, the output length changes:
result <- Reduce(`+`, c(1, 2, 3), accumulate = TRUE)
length(result)
# [1] 3
See Also
- /reference/base-functions/lapply — list apply, runs a function on each element independently
- /reference/base-functions/intersect — set intersection for working with collections
- /reference/tidyverse/purrr_reduce — tidyverse-style reduction with better edge case handling