How to find the combination of matrix values in R?


To find the combination of matrix values in R, we can use expand.grid function with split function.

For example, if we have a matrix called M then to create the combination of matrix values we can use the code mentioned below −

do.call(expand.grid,split(M,rep(1:nrow(M),ncol(M))))

Check out the examples given below to understand how it works.

Example 1

Following snippet creates a matrix −

M1<-matrix(rpois(10,2),ncol=5)
M1

Output

The following matrix is created −

    [,1] [,2] [,3] [,4] [,5]
[1,]  1   1    3    3    3
[2,]  1   3    2    1    1

In order to find the combination of matrix values in R, add the following code to the above snippet −

M1<-matrix(rpois(10,2),ncol=5)
do.call(expand.grid,split(M1,rep(1:nrow(M1),ncol(M1))))

Output

If you execute all the above given snippets as a single program, it generates the following output −

   1  2
1  1  1
2  1  1
3  3  1
4  3  1
5  3  1
6  1  3
7  1  3
8  3  3
9  3  3
10 3  3
11 1  2
12 1  2
13 3  2
14 3  2
15 3  2
16 1  1
17 1  1
18 3  1
19 3  1
20 3  1
21 1  1
22 1  1
23 3  1
24 3  1
25 3  1

Example 2

Following snippet creates a matrix −

M2<-matrix(rpois(9,2),ncol=3)
M2

Output

The following matrix is created −

    [,1][,2] [,3]
[1,] 3   1    3
[2,] 0   2    1
[3,] 5   1    0

In order to find the combination of matrix values in R, add the following code to the above snippet −

M2<-matrix(rpois(9,2),ncol=3)
do.call(expand.grid,split(M2,rep(1:nrow(M2),ncol(M2))))

Output

If you execute all the above given snippets as a single program, it generates the following output −

   1  2  3
1  3  0  5
2  1  0  5
3  3  0  5
4  3  2  5
5  1  2  5
6  3  2  5
7  3  1  5
8  1  1  5
9  3  1  5
10 3  0  1
11 1  0  1
12 3  0  1
13 3  2  1
14 1  2  1
15 3  2  1
16 3  1  1
17 1  1  1
18 3  1  1
19 3  0  0
20 1  0  0
21 3  0  0
22 3  2  0
23 1  2  0
24 3  2  0
25 3  1  0
26 1  1  0
27 3  1  0

Updated on: 05-Nov-2021

407 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements