所有可能的组合组合

时间:2015-01-12 09:51:14

标签: r combinatorics

我有5组:G1,G2,...,G5,每组分别有n1,n2,...,n5元素。我从4组中的每一组中选择2个元素,从第5组中选择1个元素。如何在R中生成所有可能的组合?

1 个答案:

答案 0 :(得分:0)

(问题中没有说明这些组是否相互排斥;因此,假设:
1。这些群体是相互排斥的 2。组(n1,n2,...)的子集将在填充时使用相同的元素。
3 仅仅为了参数| G1 | = | G2 | = | G3 | = 5(用户可以根据组中不同数量的元素相应地更改以下代码) 以下是任何用户可以概括为任意数量的组的问题的3组模拟答案。因此,假设组名是G1,G2,G3。

library(causfinder)
gctemplate(5,2,2) # Elements are coded as: 1,2,3,4,5; |sub-G1|=2; |sub-G2|=2; |sub-G3|=5-(2+2)=1
# In the following table, each number represents a unique element. (SOLUTION ENDED!)

我的包裹(causfinder)不在CRAN中。因此,我将在下面给出函数gctemplate的代码。

      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    2    3    4    5   sub-G1={1,2}  sub-G2={3,4} sub-G3={5}
 [2,]    1    2    3    5    4
 [3,]    1    2    4    5    3   sub-G1={1,2}  sub-G2={4,5} sub-G3={3}
 [4,]    1    3    2    4    5
 [5,]    1    3    2    5    4
 [6,]    1    3    4    5    2
 [7,]    1    4    2    3    5
 [8,]    1    4    2    5    3
 [9,]    1    4    3    5    2
[10,]    1    5    2    3    4
[11,]    1    5    2    4    3
[12,]    1    5    3    4    2
[13,]    2    3    1    4    5
[14,]    2    3    1    5    4
[15,]    2    3    4    5    1
[16,]    2    4    1    3    5
[17,]    2    4    1    5    3
[18,]    2    4    3    5    1
[19,]    2    5    1    3    4
[20,]    2    5    1    4    3
[21,]    2    5    3    4    1
[22,]    3    4    1    2    5
[23,]    3    4    1    5    2
[24,]    3    4    2    5    1
[25,]    3    5    1    2    4
[26,]    3    5    1    4    2
[27,]    3    5    2    4    1
[28,]    4    5    1    2    3
[29,]    4    5    1    3    2
[30,]    4    5    2    3    1

gctemplate的代码:

gctemplate <- function(nvars, ncausers, ndependents){
independents <- combn(nvars, ncausers)
patinajnumber <-  dim(combn(nvars - ncausers, ndependents))[[2]]
independentspatinajednumber <- dim(combn(nvars, ncausers))[[2]]*patinajnumber 
dependents <- matrix(, nrow = dim(combn(nvars, ncausers))[[2]]*patinajnumber, ncol = ndependents)
for (i in as.integer(1:dim(combn(nvars, ncausers))[[2]])){   
dependents[(patinajnumber*(i-1)+1):(patinajnumber*i),] <- t(combn(setdiff(seq(1:nvars), independents[,i]), ndependents))
}
independentspatinajed <- matrix(, nrow = dim(combn(nvars, ncausers))[[2]]*patinajnumber, ncol = ncausers)
for (i in as.integer(1:dim(combn(nvars, ncausers))[[2]])){   
for (j in as.integer(1:patinajnumber)){   
independentspatinajed[(i-1)*patinajnumber+j,] <- independents[,i]  
}}
independentsdependents <- cbind(independentspatinajed, dependents)
others <- matrix(, nrow = dim(combn(nvars, ncausers))[[2]]*patinajnumber, ncol = nvars - ncausers - ndependents) 
for (i in as.integer(1:((dim(combn(nvars, ncausers))[[2]])*patinajnumber))){  
others[i, ]  <- setdiff(seq(1:nvars), independentsdependents[i,]) 
}
causalitiestemplate <- cbind(independentsdependents, others)
causalitiestemplate
}

现在,G1,G2,G3的解决方案如上所述。只需使用相同的逻辑将上面的代码概括为5变量的情况!