2015-01-12 206 views
0

我有5組:G1,G2,...,G5分別與每個組中的n1,n2,...,n5元素。我從4組中選擇2個元素,從第5組中選擇1個元素。我如何在R中生成所有可能的組合?所有可能的組合組合

+4

看看'?combn'和'?expand.grid'。除此之外,請嘗試提供*真實*數據集和所需的輸出 –

+0

您的小組是否相互排斥?即組可以與其他組具有相同的元素嗎?請明確說明。如果他們是mut。 EXC。那麼我們可以將數字分配給組元素並嘗試解決您的問題。 –

回答

0

(它不是在問題中指定的組是否是相互排斥的與否;所以,假設:
1.基團是相互排斥的
2.子集組(N1,N2的,...)將在填充時使用相同的元素)
僅用於參數| 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變量情況!