[R] Pairwise combination

David Winsemius dwinsemius at comcast.net
Tue May 11 23:10:44 CEST 2010


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

> On Tuesday 11 May 2010 4:27:01 pm David Winsemius wrote:
>> On May 11, 2010, at 1:45 PM, chen jia wrote:
>>> 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.
>>
>> ?combn
>>
>>> 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).
>>
>> That's not a vector.
>
> True, although it is possible the OP wanted paste(combn(1:4, 2)[1,],  
> "and",
> combn(1:4, 2)[2,])

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.


>
> -Ista
>
>>
>>> The
>>> representation here is generic.

Whatever that meant.

>>>
>>> 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


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list