Reputation: 61
From a number of items (n), how do I compute all possible combinations of pairs in R? I can calculate the number of possible combinations with (n-1)*(n-3)*(n-5)*…
, but how to get the combinations themselves?
For example, I have
x <- c("A", "B", "C", "D")
That would make 4-1=3
combinations of pairs, so I want to have something like
("AB","CD")
("AC","BD")
("AD","BC")
Thanks a lot!
Upvotes: 1
Views: 3415
Reputation: 93871
First, let's get all pairs of pairs:
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"
We now have all pairs of pairs. But it looks like you want only pairs of pairs where each letter appears only once. The code below identifies rows that meet this condition (though it seems like the code is more complicated than it needs to be).
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"
Upvotes: 5
Reputation: 2652
For that you can use either combn
or 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"
Upvotes: 3