【问题标题】:How to calculate permutations of group labels with R?如何用 R 计算组标签的排列?
【发布时间】:2015-04-15 14:50:45
【问题描述】:

给定一个向量:

labels <- c(1,2,3,3,3)

如何获得所有可能的 group 重新标记?对于这个例子:

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

我一直在查看permute 包,但我不知道如何将其应用于此案例。

【问题讨论】:

  • 你试过permncombinat吗?
  • @khashaa 发表评论后,我只是在阅读组合文档。
  • 是的,permute 还不能进行这种类型的排列。这已经在其他一些情况下出现了,所以我希望将这种类型的排列添加到包中,但我在接下来的几个月里忙于日常工作。
  • 不要将解决方案添加到您的问题中。相反,您应该添加一个答案。

标签: r permutation permute


【解决方案1】:

这个解决方案怎么样

labels <- c(1,2,3,3,3)
library(data.table)
a <- do.call(cbind, combinat::permn(unique(labels)))
data.table(a)[,lapply(.SD, function(x)x[labels]),]
#   V1 V2 V3 V4 V5 V6
#1:  1  1  3  3  2  2
#2:  2  3  1  2  3  1
#3:  3  2  2  1  1  3
#4:  3  2  2  1  1  3
#5:  3  2  2  1  1  3

或者,只是

apply(a, 2, function(x) x[labels])
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    1    1    3    3    2    2
#[2,]    2    3    1    2    3    1
#[3,]    3    2    2    1    1    3
#[4,]    3    2    2    1    1    3
#[5,]    3    2    2    1    1    3

【讨论】:

    【解决方案2】:

    我按照建议在这里发布我自己的解决方案:

    library(combinat)
    
    labels <- c(1,2,3,3,3)
    
    group.perms <- permn(unique(labels)) 
    for(i in 1:length(group.perms)){
      cat(match(labels, group.perms[[i]]), "\n")
    }
    
    #2 1 3 3 3 
    #3 1 2 2 2 
    #3 2 1 1 1 
    #2 3 1 1 1 
    #1 3 2 2 2 
    #1 2 3 3 3 
    

    (但我更喜欢@Khashaa 提出的第二种解决方案)

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多