How to calculate permutations of group labels with R?

落爺英雄遲暮 提交于 2021-01-27 19:22:29

问题


Given a vector like:

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

How to get all possible group relabelings? For this example:

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

I have been looking at the permute package but I don't see how to apply it to this case.


回答1:


How about this solution

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

Or, just

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:


I post here my own solution as suggested:

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 

(but I like the second solution proposed by @Khashaa better)



来源:https://stackoverflow.com/questions/29653503/how-to-calculate-permutations-of-group-labels-with-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!