Learn R Programming

iterors (version 1.0)

reduce: 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 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)

Value

The result of accumulation.

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.

Author

Peter Meilstrup

Examples

Run this code
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')

Run the code above in your browser using DataLab