P. Denelle
P. Denelle

Reputation: 830

R: generate all unique permutations from a vector

I have a vector in which certain entries are repeated. From this vector, I want to obtain every possible and unique permutations.

Looking around, I saw that gtools::permutations() was recommended a few times but it cannot solve my issue.

I found a way with RcppAlgos::permuteGeneral() but the problem is that it treats every entry as a unique value and then I have to remove the duplicates in a second step. This can cause memory issue.

Is there a simple and fast way to get all the unique permutations from a vector?

Here is a reproducible example:

library(RcppAlgos)
ex <- c("sp1", "sp2", "sp2") # sp2 is repeated twice

perm <- permuteGeneral(v = ex, m = length(ex), repetition = FALSE, freqs = NULL)
perm <- as.data.frame(perm)
perm # some rows are identical (rows 1&2; 3&5, 4&6)
   V1  V2  V3
1 sp1 sp2 sp2
2 sp1 sp2 sp2
3 sp2 sp1 sp2
4 sp2 sp2 sp1
5 sp2 sp1 sp2
6 sp2 sp2 sp1

perm[!duplicated(perm), ] # this is what I want
   V1  V2  V3
1 sp1 sp2 sp2
3 sp2 sp1 sp2
4 sp2 sp2 sp1

Upvotes: 4

Views: 272

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101317

You can try unique + perms

> unique(pracma::perms(ex))
     [,1]  [,2]  [,3]
[1,] "sp2" "sp2" "sp1"
[2,] "sp2" "sp1" "sp2"
[3,] "sp1" "sp2" "sp2"

or we can do like this

permuteGeneral(
  v = unique(ex),
  m = length(ex),
  freqs = table(ex)
)

which gives

     [,1]  [,2]  [,3]
[1,] "sp1" "sp2" "sp2"
[2,] "sp2" "sp1" "sp2"
[3,] "sp2" "sp2" "sp1"

Upvotes: 2

G. Grothendieck
G. Grothendieck

Reputation: 269526

Use it like this:

library(RcppAlgos)

tab <- table(ex)
permuteGeneral(v = names(tab), freq = tab)
##      [,1]  [,2]  [,3] 
## [1,] "sp1" "sp2" "sp2"
## [2,] "sp2" "sp1" "sp2"
## [3,] "sp2" "sp2" "sp1"

Upvotes: 5

Related Questions