Iterator that generates all combinations of a vector taken m at a time.
Source:R/icombinations.R
icombinations.Rd
Constructs an iterator generates all combinations of a vector taken m
at a time. This function is similar to combn
.
Arguments
- object
vector
- m
the length of each combination
- replacement
Generate combinations with replacement? Default: no.
Details
By default, the combinations are without replacement so that elements are
not repeated. To generate combinations with replacement, set
replacement=TRUE
.
The function implementation is loosely based on the combinations
function from Python's itertools. Combinations with replacement are based on
combinations_with_replacement
from the same Python library.
Examples
# Combinations without replacement
it <- icombinations(1:4, m=2)
nextOr(it, NA) # c(1, 2)
#> [1] 1 2
nextOr(it, NA) # c(1, 3)
#> [1] 1 3
nextOr(it, NA) # c(1, 4)
#> [1] 1 4
nextOr(it, NA) # c(2, 3)
#> [1] 2 3
nextOr(it, NA) # c(2, 4)
#> [1] 2 4
nextOr(it, NA) # c(3, 4)
#> [1] 3 4
# Combinations without replacement
it <- icombinations(1:4, m=2, replacement=TRUE)
nextOr(it, NA) # c(1, 1)
#> [1] 1 1
nextOr(it, NA) # c(1, 2)
#> [1] 1 2
nextOr(it, NA) # c(1, 3)
#> [1] 1 3
nextOr(it, NA) # c(1, 4)
#> [1] 1 4
nextOr(it, NA) # c(2, 2)
#> [1] 2 2
nextOr(it, NA) # c(2, 3)
#> [1] 2 3
nextOr(it, NA) # c(2, 4)
#> [1] 2 4
nextOr(it, NA) # c(3, 3)
#> [1] 3 3
nextOr(it, NA) # c(3, 4)
#> [1] 3 4
nextOr(it, NA) # c(4, 4)
#> [1] 4 4
it3 <- icombinations(1:5, m=2)
as.list(it3)
#> [[1]]
#> [1] 1 2
#>
#> [[2]]
#> [1] 1 3
#>
#> [[3]]
#> [1] 1 4
#>
#> [[4]]
#> [1] 1 5
#>
#> [[5]]
#> [1] 2 3
#>
#> [[6]]
#> [1] 2 4
#>
#> [[7]]
#> [1] 2 5
#>
#> [[8]]
#> [1] 3 4
#>
#> [[9]]
#> [1] 3 5
#>
#> [[10]]
#> [1] 4 5
#>
utils::combn(x=1:5, m=2, simplify=FALSE)
#> [[1]]
#> [1] 1 2
#>
#> [[2]]
#> [1] 1 3
#>
#> [[3]]
#> [1] 1 4
#>
#> [[4]]
#> [1] 1 5
#>
#> [[5]]
#> [1] 2 3
#>
#> [[6]]
#> [1] 2 4
#>
#> [[7]]
#> [1] 2 5
#>
#> [[8]]
#> [1] 3 4
#>
#> [[9]]
#> [1] 3 5
#>
#> [[10]]
#> [1] 4 5
#>