首页 > 解决方案 > 具有重复元素的样本的 2 到 2 的排列

问题描述

如何获得具有重复元素的列表的所有可能排列?例如, 2 by 与x = x (1,2,2)我想要重复排列的向量:

1 1
1 2
1 2
2 1
2 2
2 2
2 1
2 2
2 2

标签: rpermutation

解决方案


使用用于生成重复排列的众多软件包之一很容易实现这一点。

library(gtools)
gtools::permutations(3, 2, c(1, 2, 2), set = FALSE, repeats.allowed = TRUE)
     [,1] [,2]
[1,]    1    1
[2,]    1    2
[3,]    1    2
[4,]    2    1
[5,]    2    2
[6,]    2    2
[7,]    2    1
[8,]    2    2
[9,]    2    2

library(arrangements)
arrangements::permutations(x = c(1,2,2), k = 2, replace = TRUE)
## output same as above

library(RcppAlgos) ### I am the author
RcppAlgos::permuteGeneral(c(1,2,2), 2, TRUE)
## output same as above

推荐阅读