How to repeat a whole matrix in R?



To repeat a whole matrix in R, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use rep function to repeat the matrix.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(80,10),ncol=4)
M

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

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

Repeat the whole matrix

Using rep function to repeat the matrix M two times −

M<-matrix(rpois(80,10),ncol=4)
M[rep(1:nrow(M),2),]

Output

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

Advertisements