Skip to content

Instantly share code, notes, and snippets.

@randy3k
Last active November 30, 2017 18:43
Show Gist options
  • Save randy3k/10015496 to your computer and use it in GitHub Desktop.
Save randy3k/10015496 to your computer and use it in GitHub Desktop.
# it is a tutorial to generate permuations/combinations using `partitions`, `gtools` and `multicool`.
# mainly for reference only, consider the package `iterpc` in practice.
library(partitions)
library(gtools)
library(multicool)
1) combinations: without replacement: distinct items
n = 5; r = 3
combn(n, r)
gtools::combinations(n, r)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 4
[3,] 1 2 5
[4,] 1 3 4
[5,] 1 3 5
.....
2) combinations: with replacement: distinct items
n = 5; r = 3
gtools::combinations(n, r, repeats.allowed=TRUE)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 2
[3,] 1 1 3
[4,] 1 1 4
[5,] 1 1 5
.....
3) combinations: without replacement: non distinct items
x = c(1,2,3,4,4)
r = 3
comb = function(x, r) {
f = tabulate(x)
ux = unique(x)
bp = partitions::blockparts(f, r)
t(apply(bp, 2, function(d) rep(ux, d)))
}
comb(x, r)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 4
[3,] 1 3 4
[4,] 2 3 4
[5,] 1 4 4
.....
4) combinations: with replacement: non distinct items
x = c(1,2,3,4,4)
r = 3
gtools::combinations(length(unique(x)), r, x, repeats.allowed=TRUE)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 2
[3,] 1 1 3
[4,] 1 1 4
[5,] 1 2 2
.....
5) permutations: without replacement: distinct items
n = 5; r = 3
gtools::permutations(n, r)
# if n=r
partitions::perms(n)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 4
[3,] 1 2 5
[4,] 1 3 2
[5,] 1 3 4
.....
6) permutations: with replacement: distinct items
n = 5; r = 3
gtools::permutations(n, r, repeats.allowed=TRUE)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 2
[3,] 1 1 3
[4,] 1 1 4
[5,] 1 1 5
.....
7) permutations: without replacement: non distinct items
x = c(1,2,3,4,4)
# if n=r
multicool::allPerm(multicool::initMC(x))
# if n>r, use the function comb in 3)
plainperm = function(x) multicool::allPerm(multicool::initMC(x))
perm = function(x, r) do.call(rbind, apply(comb(x, r), 1, plainperm))
r = 3
perm(x, r)
[,1] [,2] [,3]
[1,] 3 2 1
[2,] 1 3 2
[3,] 3 1 2
[4,] 2 3 1
[5,] 1 2 3
.....
8) permutations: with replacement: non distinct items
x = c(1,2,3,4,4)
r = 3
gtools::permutations(length(unique(x)), r, x, repeats.allowed=TRUE)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 2
[3,] 1 1 3
[4,] 1 1 4
[5,] 1 2 1
.....
@Arif8675
Copy link

Hi, can we apply this function on a matrix?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment