reduce
Reduce a list to a single value by iteratively applying a binary function.
reduce()
combines from the left, reduce_right()
combines from
the right. reduce(list(x1, x2, x3), f)
is equivalent to
f(f(x1, x2), x3)
; reduce_right(list(x1, x2, x3), f)
is equivalent to
f(f(x3, x2), x1)
.
Usage
reduce(.x, .f, ..., .init)reduce_right(.x, .f, ..., .init)
reduce2(.x, .y, .f, ..., .init)
reduce2_right(.x, .y, .f, ..., .init)
Arguments
- .x
A list or atomic vector.
- .f
For
reduce()
, a 2-argument function. The function will be passed the accumulated value as the first argument and the "next" value as the second argument.For
reduce2()
, a 3-argument function. The function will be passed the accumulated value as the first argument, the next value of.x
as the second argument, and the next value of.y
as the third argument.- ...
Additional arguments passed on to
.f
.- .init
If supplied, will be used as the first value to start the accumulation, rather than using
x[[1]]
. This is useful if you want to ensure thatreduce
returns a correct value when.x
is empty. If missing, andx
is empty, will throw an error.- .y
For
reduce2()
, an additional argument that is passed to.f
. Ifinit
is not set,.y
should be 1 element shorter than.x
.
Examples
# NOT RUN {
1:3 %>% reduce(`+`)
1:10 %>% reduce(`*`)
paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
letters[1:4] %>% reduce(paste2)
letters[1:4] %>% reduce2(c("-", ".", "-"), paste2)
samples <- rerun(2, sample(10, 5))
samples
reduce(samples, union)
reduce(samples, intersect)
x <- list(c(0, 1), c(2, 3), c(4, 5))
x %>% reduce(c)
x %>% reduce_right(c)
# Equivalent to:
x %>% rev() %>% reduce(c)
# }