R: Reduce a list to a single value by iteratively applying a...

reduce {purrr} | R Documentation

## Reduce a list to a single value by iteratively applying a binary function.

### Description

`reduce` combines from the left, `reduce_right` combines from the right.

### Usage

    reduce(.x, .f, ..., .init)

    reduce_right(.x, .f, ..., .init)

### Arguments

`.x` | A list or atomic vector.
`.f` | A two-argument function.
`...` | 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 that `reduce` returns the correct value when `.x` is `is_empty()`.

### Examples

    1:3 %>% reduce(`+`)
    1:10 %>% reduce(`*`)

    5 %>%
      replicate(sample(10, 5), simplify = FALSE) %>%
      reduce(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)

    # Use init when you want reduce to return a consistent type when
    # given an empty lists
    list() %>% reduce(`+`)
    list() %>% reduce(`+`, .init = 0)

[Package purrr version 0.2.2 Index]