Philippe Ramirez
Philippe Ramirez

Reputation: 127

permutation list of pairs

An easy one for many of you, I'm sure, which will save my day : I need to generate a permutation set of all the pairs of a sequence of numbers. For example, for 1:6, it will give as a final result, 30 subsets, i.e. n(n-1) :

(1,2),(3,4),(5,6)
...
(1,6),(2,3),(4,5)

I need pairs, not couples, so that (3,4) and (4,3) is an unique pair.

combn(1:6,2) gives me a table with my pairs as columns, but how do I produce my list of pairs out of it?

combn(1:6,2)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
[1,]    1    1    1    1    1    2    2    2    2     3     3     3     4     4     5
[2,]    2    3    4    5    6    3    4    5    6     4     5     6     5     6     6

Thank you

Upvotes: 0

Views: 876

Answers (2)

milan
milan

Reputation: 5000

Repeat your procedure in the reversed order and rbind. For example, now both c(3,4) and c(4,3) are included. I'm using t to transpose, which makes it easier to view the data.

rbind( t(combn(1:6,2)), t(combn(6:1,2)) )

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

Upvotes: 1

markus
markus

Reputation: 26373

We can set the argument simplify = FALSE in combn such that it returns a list:

combn(1:6, 2, simplify = FALSE)
#[[1]]
#[1] 1 2
#
#[[2]]
#[1] 1 3
#
#[[3]]
#[1] 1 4
#
#[[4]]
#[1] 1 5
#...

Upvotes: 2

Related Questions