Skip to contents

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, ...)

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, ...).

Value

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

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


# 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)))
#> [1] 1 2 3
#> [1] 4 5 6
#> [1] 7 8 9
#> [1] 10

# Same as previous, but return integer vectors rather than lists
it <- i_chunk(1:10, 3, mode='integer')
repeat print(unlist(nextOr(it, break)))
#> [1] 1 2 3
#> [1] 4 5 6
#> [1] 7 8 9
#> [1] 10

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

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