Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

collect

Iterate over iterator functions


Description

loop() and collect() are helpers for iterating over iterator functions such as generators.

  • loop() takes a for loop expression in which the collection can be an iterator function.

  • collect() loops over the iterator and collects the values in a list.

Usage

collect(x, n = NULL)

loop(loop)

Arguments

x

An iterator function.

n

The number of elements to collect. If x is an infinite sequence, n must be supplied to prevent an infinite loop.

loop

A for loop expression.

Value

collect() returns a list of values; loop() returns the exhausted() sentinel, invisibly.

See Also

async_collect() for async generators.

Examples

generate_abc <- generator(function() for (x in letters[1:3]) yield(x))
abc <- generate_abc()

# Collect 1 element:
collect(abc, n = 1)

# Collect all remaining elements:
collect(abc)

# With exhausted iterators collect() returns an empty list:
collect(abc)


# With loop() you can use `for` loops with iterators:
abc <- generate_abc()
loop(for (x in abc) print(x))

coro

'Coroutines' for R

v1.0.1
MIT + file LICENSE
Authors
Lionel Henry [aut, cre], RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.