Repeating rows of a matrix based on a vector in R

You don’t need to repeat each column individually – you can repeat entire rows using a subset with repeated row indices:

## We use this as the row indices
## This will work whether `rep_vec` is a 1-column matrix
## Or if it is a vector (as implied by its name)
rep(seq_along(rep_vec), rep_vec)
[1] 1 2 2 3 3 3


M[rep(seq_along(rep_vec), rep_vec), ]
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    2    5    8
# [4,]    3    6    9
# [5,]    3    6    9
# [6,]    3    6    9

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top