给定约束时生成所有组合

时间:2012-01-28 12:04:40

标签: r combinations

如何在4个块中生成2个处理(A,B)的所有6种组合,这样在每个块中都有相同数量的A和B,使用R?

"AABB","ABAB","ABBA","BBAA","BABA","BAAB" 

P.S。组合的数量计算如下:

如果

T = #treatments

n = #treatments in each block = k*T,

组合数等于n! / [k!*k! (T times)]

谢谢

3 个答案:

答案 0 :(得分:4)

这样的事情应该有效:

library(gtools)

t <- c('A','B')
k <- 2
n <- k * length(t)

t2 <- rep(t, k)
m <- permutations(n,n)
res <- unique(apply(m,MARGIN=1,function(x) paste(t2[x],collapse='')))

--------------------------------------------------------------------
res
[1] "ABAB" "ABBA" "AABB" "BAAB" "BABA" "BBAA"

答案 1 :(得分:1)

multicool包实现了一种用于置换多重集合的算法 - 这正是您想要执行的任务。以下是它可以做的一个例子:

library(multicool)

# Create a simple convenience function
enumAllPartitions <- function(multiset) {
    m1 <-  initMC(multiset)        # Initialize the permutation object
    N <- fact(length(multiset))/   # Calculate number of permutations
         prod(fact(table(multiset)))
    sapply(seq_len(N), function(X) paste(nextPerm(m1), collapse=""))
}

# Try it out with a few different multisets
x <- c("A", "A", "B", "B")
y <- c("G", "L", "L", "L")
z <- c("X", "X", "Y", "Z", "Z")

lapply(list(x,y,z), enumAllPartitions)
[[1]]
[1] "BBAA" "ABBA" "BABA" "ABAB" "AABB" "BAAB"

[[2]]
[1] "LLLG" "GLLL" "LGLL" "LLGL"

[[3]]
 [1] "ZZYXX" "XZZYX" "ZXZYX" "ZZXYX" "XZZXY" "ZXZXY" "XZXZY" "XXZZY" "ZXXZY"
[10] "ZZXXY" "YZZXX" "ZYZXX" "XZYZX" "ZXYZX" "YZXZX" "XYZZX" "YXZZX" "ZYXZX"
[19] "XZYXZ" "ZXYXZ" "XZXYZ" "XXZYZ" "ZXXYZ" "YZXXZ" "XYZXZ" "YXZXZ" "XYXZZ"
[28] "XXYZZ" "YXXZZ" "ZYXXZ"

答案 2 :(得分:1)

使用新的iterpc包也可以实现预期的解决方案。

I <- iterpc(c(2, 2), labels=c("A", "B"), ordered=TRUE)
getall(I)

#      [,1] [,2] [,3] [,4]
# [1,] "A"  "A"  "B"  "B" 
# [2,] "A"  "B"  "A"  "B" 
# [3,] "A"  "B"  "B"  "A" 
# [4,] "B"  "A"  "A"  "B" 
# [5,] "B"  "A"  "B"  "A" 
# [6,] "B"  "B"  "A"  "A"