Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: generate all unique permutations from a vector

Tags:

r

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
like image 841
P. Denelle Avatar asked Oct 22 '25 06:10

P. Denelle


1 Answers

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"
like image 156
G. Grothendieck Avatar answered Oct 24 '25 19:10

G. Grothendieck