# How to find unique permutations if a vector contains repeated elements in R?

R ProgrammingServer Side ProgrammingProgramming

We can use permn function from combinat package to find the permutations but if we have repeated elements in the vector then the result will not have unique permutations, therefore, we need to use unique function along with the permn function. For example, if we have a vector 1, 2, 1 then the permutations will be (1 2 1), (1 1 2), (1 1 2), (1 2 1), (2 1 1), (2 1 1) and the unique permutations will be (1 2 1), (1 1 2), (2 1 1).

## Example

Live Demo

x1<-c(1,2,1,2)
x1

## Output

 1 2 1 2

Finding all permutations −

permn(x1)

[]
 1 2 1 2
[]
 1 2 2 1
[]
 1 2 2 1
[]
 2 1 2 1
[]
 2 1 1 2
[]
 1 2 1 2
[]
 1 1 2 2
[]
 1 1 2 2
[]
 1 1 2 2
[]
 1 1 2 2
[]
 1 2 1 2
[]
 2 1 1 2
[]
 2 1 2 1
[]
 1 2 2 1
[]
 1 2 2 1
[]
 1 2 1 2
[]
 2 1 1 2
[]
 2 1 2 1
[]
 2 2 1 1
[]
 2 2 1 1
[]
 2 2 1 1
[]
 2 2 1 1
[]
 2 1 2 1
[]
 2 1 1 2

Finding the unique permutations −

unique(permn(x1))

[]
 1 2 1 2
[]
 1 2 2 1
[]
 2 1 2 1
[]
 2 1 1 2
[]
 1 1 2 2
[]
 2 2 1 1

## Example

x2<-c(0,1,0) permn(x2)

[]
 0 1 0
[]
 0 0 1
[]
 0 0 1
[]
 0 1 0
[]
 1 0 0
[]
 1 0 0

unique(permn(x2))

[]
 0 1 0
[]
 0 0 1
[]
 1 0 0
Advertisements