如何生成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)]
謝謝
如何生成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)]
謝謝
像這樣的東西應該工作:
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"
multicool
pac kage實現了一個算法,用於置換multisets ---完全是你想要執行的任務。這裏有什麼可以做,例如:
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"
預期的解決方案還可以使用新的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"
副查詢:你的意思是組合數是n! /((k!)^ T)? – 2012-01-28 13:44:05
@Carl Witthoft是:-P – 2012-01-28 17:23:20