给定约束,生成所有组合 [英] Generate all combinations given a constraint
本文介绍了给定约束,生成所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在4个块中生成2种处理(A,B)的6种组合的全部,从而在每个块中使用R来获得相等数量的A和B?
How can I generate all of the 6 combinations of 2 treatments (A,B) in blocks of 4, such that in each block there is an equal number of A's and B's, using R?
"AABB","ABAB","ABBA","BBAA","BABA","BAAB"
PS组合的数量计算如下:
P.S. The number of combinations is calculated as follows:
如果
T = #treatments
n = #treatments in each block = k*T,
组合数等于 n! / [k!* k! (T次)]
谢谢
推荐答案
类似的事情应该起作用:
Something like this should work:
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"
这篇关于给定约束,生成所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文