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).

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. 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. 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 that reduce returns a correct value when .x is empty. If missing, and x is empty, will throw an error. For reduce2(), an additional argument that is passed to .f. If init is not set, .y should be 1 element shorter than .x.

## Examples

1:3 %>% reduce(+)#> [1] 61:10 %>% reduce(*)#> [1] 3628800
paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
letters[1:4] %>% reduce(paste2)#> [1] "a.b.c.d"letters[1:4] %>% reduce2(c("-", ".", "-"), paste2)#> [1] "a-b.c-d"
samples <- rerun(2, sample(10, 5))
samples#> [[1]]
#> [1]  5  8  6 10  9
#>
#> [[2]]
#> [1]  8 10  6  4  1
#> reduce(samples, union)#> [1]  5  8  6 10  9  4  1reduce(samples, intersect)#> [1]  8  6 10
x <- list(c(0, 1), c(2, 3), c(4, 5))
x %>% reduce(c)#> [1] 0 1 2 3 4 5x %>% reduce_right(c)#> [1] 4 5 2 3 0 1# Equivalent to:
x %>% rev() %>% reduce(c)#> [1] 4 5 2 3 0 1