How to combine matrix rows alternately in R?


If we have multiple matrices and we want to combine the rows of those matrices alternately then we would first need to find the order of the matrices with order function along with sequence and sapply function after reading the matrices with list after that the values will be combined with rbind function.

Check out the Example given below to understand how it can be done.

Example

Following snippet creates a sample matrix −

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

The following matrix is created −

    [,1] [,2]
 [1,] 10  7
 [2,] 6   5
 [3,] 8   3
 [4,] 4   2
 [5,] 5   5
 [6,] 6   7
 [7,] 9   5
 [8,] 1   5
 [9,] 3   3
[10,] 5   3
[11,] 5   5
[12,] 3   5
[13,] 4   7
[14,] 6   4
[15,] 3   8
[16,] 4   1
[17,] 9   2
[18,] 4   4
[19,] 6   6
[20,] 5   2

Following snippet creates a sample matrix −

M2<-matrix(rpois(40,1),ncol=2)
M2

The following matrix is created −

    [,1] [,2]
 [1,] 1   3
 [2,] 2   1
 [3,] 2   1
 [4,] 1   3
 [5,] 3   1
 [6,] 1   1
 [7,] 4   1
 [8,] 1   1
 [9,] 0   0
[10,] 0   3
[11,] 1   0
[12,] 1   1
[13,] 1   3
[14,] 0   3
[15,] 3   2
[16,] 2   0
[17,] 0   1
[18,] 1   1
[19,] 1   0
[20,] 2   0

To combine rows of M1 and M2 alternately on the above created data frame, add the following code to the above snippet −

M1<-matrix(rpois(40,5),ncol=2)
M2<-matrix(rpois(40,1),ncol=2)
do.call(rbind,list(M1,M2))[order(sequence(sapply(list(M1,M2),nrow))),]

Output

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

    [,1] [,2]
 [1,] 10  7
 [2,] 1   3
 [3,] 6   5
 [4,] 2   1
 [5,] 8   3
 [6,] 2   1
 [7,] 4   2
 [8,] 1   3
 [9,] 5   5
[10,] 3   1
[11,] 6   7
[12,] 1   1
[13,] 9   5
[14,] 4   1
[15,] 1   5
[16,] 1   1
[17,] 3   3
[18,] 0   0
[19,] 5   3
[20,] 0   3
[21,] 5   5
[22,] 1   0
[23,] 3   5
[24,] 1   1
[25,] 4   7
[26,] 1   3
[27,] 6   4
[28,] 0   3
[29,] 3   8
[30,] 3   2
[31,] 4   1
[32,] 2   0
[33,] 9   2
[34,] 0   1
[35,] 4   4
[36,] 1   1
[37,] 6   6
[38,] 1   0
[39,] 5   2
[40,] 2   0

Updated on: 09-Nov-2021

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements