Skip to content

Pairwise combination

8 messages · Henrique Dallazuanna, David Winsemius, Ista Zahn +1 more

#
Hi there,

I am looking for a function that takes a vector as input and generates
all pair wise combination of the elements of the input vector.

For example, the input vector is c(1,2,3,4). The output vector is c(1
and 2, 1 and 3, 1 and 4, 2 and 3, 2 and 4, 3 and 4). The
representation here is generic.

I can use a for loop to do it, but it gets slow when the number of
elements of the input vector is large.

Best,
Jia
#
On May 11, 2010, at 1:45 PM, chen jia wrote:

            
?combn
That's not a vector.
David Winsemius, MD
West Hartford, CT
#
combn(1:4, 2) will do it.

-Ista
On Tuesday 11 May 2010 1:45:14 pm chen jia wrote:
#
On Tuesday 11 May 2010 4:27:01 pm David Winsemius wrote:
True, although it is possible the OP wanted paste(combn(1:4, 2)[1,], "and", 
combn(1:4, 2)[2,])

-Ista
#
On May 11, 2010, at 4:54 PM, Ista Zahn wrote:

            
True enough, but then it would look like c("1 and 2", "1 and 3", ...  
etc. Or he could have wanted a matrix, or he could have wanted:

   expand.grid(c(1,2,3,4),c(1,2,3,4))

or... any one of a number of things. If, as he said, he was already  
successful in creating whatever it was that he wanted, then he  
_should_ have offered a valid R object, so we wouldn't need to guess.
Whatever that meant.
David Winsemius, MD
West Hartford, CT
#
Thanks, everyone.

combn function works pretty well for me.

Best,
Jia
On Tue, May 11, 2010 at 5:12 PM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote: