给定“组ID”值,我需要获取2个值的所有置换

我有这个:

group id    value
   1         a
   1         b
   1         c
   2         b
   2         c
   2         d

并想要这个:
group id    value1   value2
   1         a        b
   1         a        c
   1         b        a
   1         b        c
   1         c        a
   1         c        b
   2         b        c
   2         b        d
   2         c        b
   2         c        d
   2         d        b
   2         d        c

最佳答案

下面是快速而简单的

library(gtools)
library(data.table)

indices <- c(1,1,1,2,2,2)
variables <- c("a", "b", "c", "b", "c", "d")
dt <- data.table(indices, variables)

get_permutations <- function(df){
    perm <- permutations(nrow(unique(df[,1])), 2, df$variables)
    as.data.table(perm)
}

ds <- dt[, get_permutations(.SD), by = indices]

    indices V1 V2
 1:       1  a  b
 2:       1  a  c
 3:       1  b  a
 4:       1  b  c
 5:       1  c  a
 6:       1  c  b
 7:       2  b  c
 8:       2  b  d
 9:       2  c  b
10:       2  c  d
11:       2  d  b
12:       2  d  c

10-06 13:38
查看更多