| reduce {iterors} | R Documentation |
Compute the sum, product, or general reduction of an iterator.
Description
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 class 'iteror'
reduce(obj, fun = `+`, init = 0, ...)
i_accum(obj, fun = `+`, init = 0, ...)
## S3 method for class 'iteror'
sum(..., na.rm = FALSE)
## S3 method for class '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 |
na.rm |
Whether to drop NA values when computing sum or prod. |
Value
The result of accumulation.
Author(s)
Peter Meilstrup
Examples
it <- icount(5)
total <- reduce(it, `+`) # 15
it <- icount(5)
reduce(it, paste0, "") # "12345"
it <- icount(5)
reduce(it, `*`, init=1) # 120
# triangular numbers: 1, 1+2, 1+2+3, ...
take(i_accum(icount()), 10, 'numeric')
[Package iterors version 1.0 Index]