reduce(obj, fun)
applies a 2-argument function fun
between
successive elements of obj. For example if fun
is +
,
reduce(it,
+, init=0)
computes 0 + nextElem(it) + nextElem(it) + nextElem(it) + ...
until the iterator finishes,
and returns the final value.
i_accum(obj)
returns the iterator containing
each intermediate result. The default settings
produce a cumulative sum.
sum.iteror(it)
is equivalent to reduce(it, `+`)
prod.iteror(it)
is equivalent to reduce(it, `*`)
.
Usage
reduce(obj, fun = `+`, init = 0, ...)
# S3 method for iteror
reduce(obj, fun = `+`, init = 0, ...)
i_accum(obj, fun = `+`, init = 0, ...)
# S3 method for iteror
sum(..., na.rm = FALSE)
# S3 method for iteror
prod(..., na.rm = FALSE)
Arguments
- obj
an iterable object
- fun
A function of as least two arguments.
- init
A starting value.
- ...
Extra parameters will be passed to each call to fun
.
- na.rm
Whether to drop NA values when computing sum or prod.
Value
The result of accumulation.
Examples
it <- icount(5)
total <- reduce(it, `+`) # 15
it <- icount(5)
reduce(it, paste0, "") # "12345"
#> [1] "12345"
it <- icount(5)
reduce(it, `*`, init=1) # 120
#> [1] 120
# triangular numbers: 1, 1+2, 1+2+3, ...
take(i_accum(icount()), 10, 'numeric')
#> [1] 1 3 6 10 15 21 28 36 45 55