reduce
From purrr v0.2.2.2
by Lionel Henry
Reduce a list to a single value by iteratively applying a binary function.
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 thatreduce
returns the correct value when.x
isis_empty()
.
Examples
# NOT RUN {
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)
# }
Community examples
Looks like there are no examples yet.