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] 1 2 1 2

Finding all permutations −

permn(x1)

[[1]]
[1] 1 2 1 2
[[2]]
[1] 1 2 2 1
[[3]]
[1] 1 2 2 1
[[4]]
[1] 2 1 2 1
[[5]]
[1] 2 1 1 2
[[6]]
[1] 1 2 1 2
[[7]]
[1] 1 1 2 2
[[8]]
[1] 1 1 2 2
[[9]]
[1] 1 1 2 2
[[10]]
[1] 1 1 2 2
[[11]]
[1] 1 2 1 2
[[12]]
[1] 2 1 1 2
[[13]]
[1] 2 1 2 1
[[14]]
[1] 1 2 2 1
[[15]]
[1] 1 2 2 1
[[16]]
[1] 1 2 1 2
[[17]]
[1] 2 1 1 2
[[18]]
[1] 2 1 2 1
[[19]]
[1] 2 2 1 1
[[20]]
[1] 2 2 1 1
[[21]]
[1] 2 2 1 1
[[22]]
[1] 2 2 1 1
[[23]]
[1] 2 1 2 1
[[24]]
[1] 2 1 1 2

Finding the unique permutations −

unique(permn(x1))

[[1]]
[1] 1 2 1 2
[[2]]
[1] 1 2 2 1
[[3]]
[1] 2 1 2 1
[[4]]
[1] 2 1 1 2
[[5]]
[1] 1 1 2 2
[[6]]
[1] 2 2 1 1

Example

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

[[1]]
[1] 0 1 0
[[2]]
[1] 0 0 1
[[3]]
[1] 0 0 1
[[4]]
[1] 0 1 0
[[5]]
[1] 1 0 0
[[6]]
[1] 1 0 0

unique(permn(x2))

[[1]]
[1] 0 1 0
[[2]]
[1] 0 0 1
[[3]]
[1] 1 0 0
raja
Published on 08-Oct-2020 18:19:54
Advertisements