Learn R Programming

iterors (version 1.0)

i_chunk: Combine an iterator's values into chunks.

Description

Create an iterator that issues lists of values from the underlying iterable. This is useful for manually “chunking” values from an iterable.

Usage

i_chunk(iterable, size, mode = "list", fill, ...)

Value

an iteror that yields items of length size and mode mode.

Arguments

iterable

Iterable to iterate over.

size

Maximum number of values from iterable to return in each value issued by the resulting iterator.

mode

Mode of the objects returned by the iterator.

fill

Value to use to pad the last chunk to size, if it is short. If missing, no padding will be done.

...

Further arguments will be forwarded to iteror(iterable, ...).

See Also

iteror.default

Argument size does not need to be an integer, for instance a chunk of 3.5 will produce chunks of sizes 3 and 4 alternating. The precise behavior will be subject to floating point precision.

Examples

Run this code

# Split the vector 1:10 into "chunks" with a maximum length of three
it <- i_chunk(1:10, 3)
repeat print(unlist(nextOr(it, break)))

# Same as previous, but return integer vectors rather than lists
it <- i_chunk(1:10, 3, mode='integer')
repeat print(unlist(nextOr(it, break)))

it <- i_chunk(iterators::iter(1:5), 2, fill=NA)
# List: list(1, 2, 3)
nextOr(it, NULL)
# List: list(4, 5, NA)
nextOr(it, NULL)

it2 <- i_chunk(levels(iris$Species), 4, fill="weeee")
# Returns: list("setosa", "versicolor", "virginica", "weeee")
nextOr(it2, NA)

Run the code above in your browser using DataLab