How to expand a matrix rows by their index position in R?


To expand a matrix rows by its index position in R, we can follow the below steps −

  • First of all, create a matrix.
  • Then, use rep and seq_len function with nrow to expand the matrix rows by their index position.

Create the matrix

Let’s create a matrix as shown below −

 Live Demo

M<-matrix(rnorm(18),nrow=6)
M

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

        [,1]       [,2]       [,3]
[1,] 1.1504336 -2.7945635 -1.1192209
[2,] 1.8228588 0.5034033 -0.9991265
[3,] 0.7930331 -0.1489556 -0.3942745
[4,] 0.3773271 1.4935511 0.4641247
[5,] 1.2586923 -0.2941518 -0.7457999
[6,] 0.6746511 1.7114469 1.1954979

Expand the matrix

Using rep and seq_len function with nrow to expand the rows in M by their index position −

 Live Demo

M<-matrix(rnorm(18),nrow=6)
M<-M[rep(seq_len(nrow(M)),1:6),]
M

Output

         [,1]      [,2]      [,3]
[1,] 1.1504336 -2.7945635 -1.1192209
[2,] 1.8228588 0.5034033 -0.9991265
[3,] 1.8228588 0.5034033 -0.9991265
[4,] 0.7930331 -0.1489556 -0.3942745
[5,] 0.7930331 -0.1489556 -0.3942745
[6,] 0.7930331 -0.1489556 -0.3942745
[7,] 0.3773271 1.4935511 0.4641247
[8,] 0.3773271 1.4935511 0.4641247
[9,] 0.3773271 1.4935511 0.4641247
[10,] 0.3773271 1.4935511 0.4641247
[11,] 1.2586923 -0.2941518 -0.7457999
[12,] 1.2586923 -0.2941518 -0.7457999
[13,] 1.2586923 -0.2941518 -0.7457999
[14,] 1.2586923 -0.2941518 -0.7457999
[15,] 1.2586923 -0.2941518 -0.7457999
[16,] 0.6746511 1.7114469 1.1954979
[17,] 0.6746511 1.7114469 1.1954979
[18,] 0.6746511 1.7114469 1.1954979
[19,] 0.6746511 1.7114469 1.1954979
[20,] 0.6746511 1.7114469 1.1954979
[21,] 0.6746511 1.7114469 1.1954979

Updated on: 13-Aug-2021

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements