knitr::opts_chunk$set(echo = TRUE)
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.
Install from CRAN:
install.packages("combiter")
Install development version:
devtools::install_github("kota7/combiter")
Import:
library(combiter)
This package provides four iterator classes for integer vectors: icomb
, iperm
, isubset
, and icartes
.
icomb(n, k)
goes through all combinations of k integers out of 1
to n
.iperm(n, k)
goes through all permutations of size k
consisting of integers 1
to n
of size k
.isubset(n)
goes through all subsets of integers 1
to n
.icartes(c(n1, n2, ...))
, available for v1.0.2+
, goes through cartesian products of 1
to n1
, 1
to n2
....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.
x <- icomb(5, 3) ct <- 0 while (hasNext(x)) { ct <- ct + 1 i <- nextElem(x) cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " "))) }
x <- iperm(4, 2) ct <- 0 while (hasNext(x)) { ct <- ct + 1 i <- nextElem(x) cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " "))) }
x <- isubset(3) ct <- 0 while (hasNext(x)) { ct <- ct + 1 i <- nextElem(x) cat(sprintf("%3d : %s\n", ct, paste0(i, collapse = " "))) }
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 = " "))) }
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 = " "))) }
icombv
, isubsetv
, and icartesv
are also defined analogously.
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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.