Learn R Programming

itertools2 (version 0.1.1)

ienumerate: 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.

Usage

ienumerate(object)
ienum(object)

Arguments

object
object to return indefinitely.

Value

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

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

ienum is an alias to ienumerate to save a few keystrokes.

Examples

Run this code
set.seed(42)
it <- ienumerate(rnorm(5))
as.list(it)

# Iterates through the columns of the iris data.frame
it2 <- ienum(iris)
iterators::nextElem(it2)
iterators::nextElem(it2)
iterators::nextElem(it2)
iterators::nextElem(it2)
iterators::nextElem(it2)

Run the code above in your browser using DataLab