[R] enumerating non-overlapping pairs of elements from a vector

Allan Strand stranda at cofc.edu
Mon Mar 5 15:56:28 CET 2007


Hi All,

I'm trying to come up with a clear and concise (and fast?) solution to
the following problem.

I would like to take a vector 'v' and enumerate all of the ways in
which it can be broken into n sets of length 2 (if the length of the
vector is odd, and an additional set of length 1).  An element of 'v'
can
only appear in one set. Order within sets is not important.  Vector
'v' can be of lengths 2-12

 'n' is determined by length(v)%/%2
 if length(v)%%2 is non-zero, the additional set of length 1 is used

For example vector 'v':
v = (1,2,3,4)

The solution would be (rows are combinations of sets chosen, where
each element only appears once)

1 2, 3 4
1 3, 2 4
1 4, 2 3

In the case where length(v) is odd
v = (1,2,3,4,5)
1 2, 3 4, 5
1 3, 2 4, 5
1 4, 2 3, 5
5 2, 3 4, 1
5 3, 2 4, 1
5 4, 2 3, 1
5 1, 3 4, 2
5 3, 1 4, 2
5 4, 1 3, 2
and so on...

Certainly pulling all combinations of two or one elements is not a big
deal, for example

combinations(5,2,c(1,2,3,4,5),repeats.allowed=T) 

from the 'gtools' package would do something like this.  

I'm stuck on a clean solution for enumerating all the non-overlapping
sets without some elaborate looping and checking scheme.  No doubt
this is a lapse in my understanding of combinatorics.  Any help would
be greatly appreciated

cheers,
a.



More information about the R-help mailing list