从多个项目(n)中,如何计算R中所有可能的对组合?我可以使用(n-1)*(n-3)*(n-5)*…
计算可能组合的数量,但是如何自己获得组合?
例如,我有
x <- c("A", "B", "C", "D")
这会使4-1=3
对的组合,所以我希望有类似
("AB","CD")
("AC","BD")
("AD","BC")
非常感谢!
答案 0 :(得分:5)
首先,让我们得到所有成对的对:
dat = t(combn(combn(x, 2, paste, collapse=""), 2))
[,1] [,2] [1,] "AB" "AC" [2,] "AB" "AD" [3,] "AB" "BC" [4,] "AB" "BD" [5,] "AB" "CD" [6,] "AC" "AD" [7,] "AC" "BC" [8,] "AC" "BD" [9,] "AC" "CD" [10,] "AD" "BC" [11,] "AD" "BD" [12,] "AD" "CD" [13,] "BC" "BD" [14,] "BC" "CD" [15,] "BD" "CD"
我们现在拥有所有成对配对。但看起来你只想要成对的对,每个字母只出现一次。下面的代码标识满足此条件的行(尽管代码似乎比它需要的更复杂)。
dat[sapply(strsplit(apply(dat, 1, paste, collapse=""), ""), function(i) length(unique(i)) == 4), ]
[,1] [,2] [1,] "AB" "CD" [2,] "AC" "BD" [3,] "AD" "BC"
答案 1 :(得分:1)
为此,您可以使用combn
或expand.grid
x <- c("A","B","C","D")
expand.grid(x, x) # generates both way combinations
Var1 Var2
1 A A
2 B A
3 C A
4 D A
5 A B
6 B B
7 C B
8 D B
9 A C
10 B C
11 C C
12 D C
13 A D
14 B D
15 C D
16 D D
t(combn(x, 2)) # order does not matter
[,1] [,2]
[1,] "A" "B"
[2,] "A" "C"
[3,] "A" "D"
[4,] "B" "C"
[5,] "B" "D"
[6,] "C" "D"