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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With