Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all possible n choose 2 pairs from a vector in R, efficient and fast [duplicate]

Tags:

r

Imagine I have a vector x and i'd like to create a matrix with all the possible n choose 2 combinations of the elements of x.

More in detail, let us say x is,

x = c(1,2,3,4)

Then, all the possible (4 choose 2) = 6,

X = as.matrix(data.frame(col1 = c(1,1,1,2,2,3), col2 = c(2,3,4,3,4,4)))

Is there a function in R to do that?

like image 827
Dnaiel Avatar asked Nov 15 '13 15:11

Dnaiel


1 Answers

As pointed out by @Arun, you can use combn

> t(combn(x, 2))
     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    1    4
[4,]    2    3
[5,]    2    4
[6,]    3    4
like image 113
Jilber Urbina Avatar answered Oct 12 '22 01:10

Jilber Urbina