以下は、x の要素を n 個のグループに分割するすべての可能な組み合わせを作成する関数です (すべてのグループは同じ数の要素を持ちます)。
関数:
perm.groups <- function(x,n){
nx <- length(x)
ning <- nx/n
group1 <-
rbind(
matrix(rep(x[1],choose(nx-1,ning-1)),nrow=1),
combn(x[-1],ning-1)
)
ng <- ncol(group1)
if(n > 2){
out <- vector('list',ng)
for(i in seq_len(ng)){
other <- perm.groups(setdiff(x,group1[,i]),n=n-1)
out[[i]] <- lapply(seq_along(other),
function(j) cbind(group1[,i],other[[j]])
)
}
out <- unlist(out,recursive=FALSE)
} else {
other <- lapply(seq_len(ng),function(i)
matrix(setdiff(x,group1[,i]),ncol=1)
)
out <- lapply(seq_len(ng),
function(i) cbind(group1[,i],other[[i]])
)
}
out
}
擬似コード (説明)
nb = number of groups
ning = number of elements in every group
if(nb == 2)
1. take first element, and add it to every possible
combination of ning-1 elements of x[-1]
2. make the difference for each group defined in step 1 and x
to get the related second group
3. combine the groups from step 2 with the related groups from step 1
if(nb > 2)
1. take first element, and add it to every possible
combination of ning-1 elements of x[-1]
2. to define the other groups belonging to the first groups obtained like this,
apply the algorithm on the other elements of x, but for nb-1 groups
3. combine all possible other groups from step 2
with the related first groups from step 1
この関数 (および疑似コード) は、Joris Meys によってこの以前の投稿で最初に作成されました: Find all possible ways to split a list of elements into aa given number of group of group of the same size
指定された数のランダムに可能な組み合わせを返す関数を作成する方法はありますか? このような関数は、関数が返すランダムな異なる組み合わせの数を修正する、percentage.possibilities または number.possiblities のいずれかである 3 番目の引数を取ります。
何かのようなもの:
new.perm.groups(x=1:12,n=3,number.possiblities=50)