i_enumerate {iterors}R Documentation

Iterator that returns the elements of an object along with their indices

Description

Constructs an iterator that returns the elements of an object along with each element's indices. Enumeration is useful when looping through an object and a counter is required.

The i_enumerate method for arrays allows splitting an array by arbitrary margins, including by multiple margins. The index element returned will be a vector (or if chunking is used, a matrix) of indices.

Usage

i_enumerate(obj, ...)

ienumerate(obj, ...)

## Default S3 method:
i_enumerate(obj, ..., recycle = FALSE, chunkSize, chunks)

i_enum(obj, ...)

## S3 method for class 'array'
i_enumerate(
  obj,
  ...,
  recycle = FALSE,
  chunkSize,
  chunks,
  by = c("cell", "row", "column"),
  rowMajor = TRUE,
  drop = FALSE
)

Arguments

obj

object to return indefinitely.

...

Undocumented.

recycle

Whether to restart the iterator after finishing the array.

chunkSize

How large a chunk to take along the specified dimension.

chunks

How many chunks to divide the array into.

by

Which array margins to iterate over. Can be "row", "col", "cell", or a vector of numerical indices.

rowMajor

If TRUE, the first index varies fastest, if FALSE, the last index varies fastest.

drop

Whether to drop marginalized dimensions. If chunking is used, this has no effect.

Details

This function is intended to follow the convention used in Python's enumerate function where the primary difference is that a list is returned instead of Python's tuple construct.

Each call to nextElem returns a list with two elements:

index:

a counter

value:

the current value of object

i_enum is an alias to i_enumerate to save a few keystrokes.

First appeared in package iterators2.

These are two closely closely related functions: i_enumerate accepts an iterable, and will only emit a single index starting with 1. ienumerate is a generic with methods for vectors and arrays, supporting all chunking and recycling options, and returning multiple indices for arrays.

Value

iterator that returns the values of obj along with the index of the object.

Author(s)

Peter Meilstrup

Examples

set.seed(42)
it <- i_enumerate(rnorm(5))
as.list(it)

# Iterates through the columns of the iris data.frame
it2 <- i_enum(iris)
nextOr(it2, NA)
nextOr(it2, NA)
nextOr(it2, NA)
nextOr(it2, NA)
nextOr(it2, NA)

a <- array(1:27, c(3, 3, 3))
as.list(i_enumerate(a, by=c(1, 2), drop=TRUE))
as.list(i_enumerate(a, by=c(3), drop=FALSE))
as.list(i_enumerate(a, by=c(2, 3), chunkSize=7))

[Package iterors version 1.0 Index]