15

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?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Dnaiel
  • 7,622
  • 23
  • 67
  • 126

1 Answers1

26

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
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138