r - 在 R 中打印不重复的组合

标签 r combinatorics

我想在 R 中获得以下打印输出:

1,2,3
1,2,4
1,3,4

2,1,3
2,1,4
2,3,4

3,1,2
3,1,4
3,2,4

4,1,2
4,1,3
4,2,3

大致如下:

for (main in 1:4){
  for (i in 1:4) {
    if (i != main){
      for (j in 1:4){
        if (j != main & j != i){print main,i,j}}}}}

我希望将以上 12 个结果放入向量中。谢谢。

最佳答案

正如评论中所指出的,这是排列和组合之间的奇怪组合。这是一个可能的解决方案:

Reduce(rbind,
  lapply(1:4, function(i){
    t(rbind(i, combn((1:4)[-i], 2)))
  })
)
#>       i    
#>  [1,] 1 2 3
#>  [2,] 1 2 4
#>  [3,] 1 3 4
#>  [4,] 2 1 3
#>  [5,] 2 1 4
#>  [6,] 2 3 4
#>  [7,] 3 1 2
#>  [8,] 3 1 4
#>  [9,] 3 2 4
#> [10,] 4 1 2
#> [11,] 4 1 3
#> [12,] 4 2 3

关于r - 在 R 中打印不重复的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50928284/

相关文章:

r - 在特定模式之前子集字符串的一部分

r - 使用facet_wrap时显示每个散点图的回归方程和R^2

matlab - 有效地找到独特的排列

algorithm - 旅行商 (TSP) : what is the Relation with number of vertices and length of the found route?

r - 如何在 RStudio 中逐段运行代码?

r - 无法绘制 rlm 对象。非 NA 剩余长度与拟合中使用的情况不匹配

r - 是否可以在 testthat 中确定测试顺序?

algorithm - secret 圣诞老人 - 生成 'valid' 排列

.net - 生成 .NET 中多个列的所有可能组合

php - 获取特定数字的所有变体特定长度和特定最小值和最大值?