Search code examples
runique

Generating unique pairs from R vector


I have a R vector as follows:

v <- c(2,3,4,5)

I would like to generate unique pairs from this list so:

(2,3), (2,4), (2,5), (3,4), (3,5), (4,5)

Without the same element being repeated twice, so no (2,2) or (3,3) and moreover one can treat (2,3) the same as (3,2) and so on.

How could one do this in R?

Thanks!


Solution

  • combn(v, 2)
    #     [,1] [,2] [,3] [,4] [,5] [,6]
    #[1,]    2    2    2    3    3    4
    #[2,]    3    4    5    4    5    5
    

    or combn(unique(v), 2) if necessary.