How to create a combination of pairs from a vector in R?


To create a combination of pairs, we can use the combn function. This function will be helpful to use the vector length and the value 2 that represents a pair to create the combinations. Although, this is enough but we can transpose the output to get a better−looking output.

Example1

 Live Demo

x1<−rpois(6,5)
x1

Output

[1] 5 3 7 4 8 2

Creating pair combinations for values of x1 −

Example

t(combn(x1,2))

Output

[,1] [,2]
[1,] 5 3
[2,] 5 7
[3,] 5 4
[4,] 5 8
[5,] 5 2
[6,] 3 7
[7,] 3 4
[8,] 3 8
[9,] 3 2
[10,] 7 4
[11,] 7 8
[12,] 7 2
[13,] 4 8
[14,] 4 2
[15,] 8 2

Example2

 Live Demo

x2<−LETTERS[1:5]

Creating pair combinations for values of x2 −

Example

t(combn(x2,2))

Output

[,1] [,2]
[1,] "A" "B"
[2,] "A" "C"
[3,] "A" "D"
[4,] "A" "E"
[5,] "B" "C"
[6,] "B" "D"
[7,] "B" "E"
[8,] "C" "D"
[9,] "C" "E"
[10,] "D" "E"

Example3

 Live Demo

x3<−c("F1","F2","F3","F4","F5","F6")

Creating pair combinations for values of x3 −

Example

t(combn(x3,2))

Output

[,1] [,2]
[1,] "F1" "F2"
[2,] "F1" "F3"
[3,] "F1" "F4"
[4,] "F1" "F5"
[5,] "F1" "F6"
[6,] "F2" "F3"
[7,] "F2" "F4"
[8,] "F2" "F5"
[9,] "F2" "F6"
[10,] "F3" "F4"
[11,] "F3" "F5"
[12,] "F3" "F6"
[13,] "F4" "F5"
[14,] "F4" "F6"
[15,] "F5" "F6"

Example4

 Live Demo

x4<−sample(0:9,5)
x4

Output

[1] 5 6 2 7 4

Creating pair combinations for values of x4 −

Example

t(combn(x4,2))

Output

[,1] [,2]
[1,] 5 6
[2,] 5 2
[3,] 5 7
[4,] 5 4
[5,] 6 2
[6,] 6 7
[7,] 6 4
[8,] 2 7
[9,] 2 4
[10,] 7 4

Example5

 Live Demo

x5<−round(rnorm(5),0)
x5

Output

[1] 0 1 −1 1 0

Creating pair combinations for values of x5 −

Example

t(combn(x5,2))

Output

[,1] [,2]
[1,] 0 1
[2,] 0 −1
[3,] 0 1
[4,] 0 0
[5,] 1 −1
[6,] 1 1
[7,] 1 0
[8,] −1 1
[9,] −1 0
[10,] 1 0

Updated on: 08-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements