docs/index.md

combiter: Combinatorics Iterators for R

Build Status CRAN Status

Overview

This package provides iterators for combinations, permutations, subsets, and cartesian product, with which one can go through the elements without creating a huge set of all possible values.

Since v1.0.2, the iterator objects of the package inherit the iter class from iterators package. As a result, the objects are also compatible with foreach library.

Installation and Import

Install from CRAN:

install.packages("combiter")

Install development version:

devtools::install_github("kota7/combiter")

Import:

library(combiter)

Basic Iterators

This package provides four iterator classes for integer vectors: icomb, iperm, isubset, and icartes.

The iterators do not store all possible values inside the object. Instead, they compute the next or previous element on spot. This implementation would be more memory efficient with a large n, since the number of possible cases grows exponentially or even faster for these Combinatorics operations.

Examples

x <- icomb(5, 3)
ct <- 0
while (hasNext(x))
{
  ct <- ct + 1
  i <- nextElem(x)
  cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " ")))
}
##   1 : 1 2 3
##   2 : 1 2 4
##   3 : 1 2 5
##   4 : 1 3 4
##   5 : 1 3 5
##   6 : 1 4 5
##   7 : 2 3 4
##   8 : 2 3 5
##   9 : 2 4 5
##  10 : 3 4 5
x <- iperm(4, 2)
ct <- 0
while (hasNext(x))
{
  ct <- ct + 1
  i <- nextElem(x)
  cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " ")))
}
##   1 : 1 2
##   2 : 1 3
##   3 : 1 4
##   4 : 2 1
##   5 : 2 3
##   6 : 2 4
##   7 : 3 1
##   8 : 3 2
##   9 : 3 4
##  10 : 4 1
##  11 : 4 2
##  12 : 4 3
x <- isubset(3)
ct <- 0
while (hasNext(x))
{
  ct <- ct + 1
  i <- nextElem(x)
  cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " ")))
}
##   1 : 
##   2 : 1
##   3 : 2
##   4 : 3
##   5 : 1 2
##   6 : 1 3
##   7 : 2 3
##   8 : 1 2 3
x <- icartes(c(3, 4))
ct <- 0
while (hasNext(x))
{
  ct <- ct + 1
  i <- nextElem(x)
  cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " ")))
}
##   1 : 1 1
##   2 : 1 2
##   3 : 1 3
##   4 : 1 4
##   5 : 2 1
##   6 : 2 2
##   7 : 2 3
##   8 : 2 4
##   9 : 3 1
##  10 : 3 2
##  11 : 3 3
##  12 : 3 4

Iterate through Values (v1.0.2+)

Each iterator shown above has its value counterpart. For example, ipermv, the value version of iperm, iterates through all permutations of k elements from n values.

x <- ipermv(c("A", "G", "C"), 2)
ct <- 0
while (hasNext(x))
{
  ct <- ct + 1
  i <- nextElem(x)
  cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " ")))
}
##   1 : A G
##   2 : A C
##   3 : G A
##   4 : G C
##   5 : C A
##   6 : C G

icombv, isubsetv, and icartesv are also defined analogously.

Use with foreach (v1.0.2+)

Since v1.0.2, the iterator objects can be used with foreach function from foreach.

library(foreach)
foreach(i = icomb(3, 2)) %do% sum(i)
## [[1]]
## [1] 3
## 
## [[2]]
## [1] 4
## 
## [[3]]
## [1] 5

Links



kota7/combiter documentation built on May 20, 2019, 1:10 p.m.