Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicate rows of a matrix in R

Tags:

r

matrix

Suppose I have a matrix m and a positive integer vector v, what I want to do is get a new matrix m_new and each row of m (say m[i, ]) are replicated by v[i] times in m_new. For example:

m = matrix(1:6, nrow = 3)
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6
v = c(3, 1, 2)

And m_new should be:

     [,1] [,2]
[1,]    1    4  # m[1, ] is replicated by
[2,]    1    4  # v[1] = 3
[3,]    1    4  # times
[4,]    2    5   
[5,]    3    6  
[6,]    3    6  

A for loop will make it for the small case:

m_new = matrix(0, sum(v), ncol(m))
k = 1
for(i in 1:nrow(m)){
    for(j in k:(k+v[i]-1)){
        m_new[j, ] = m[i, ]
    }
    k = k + v[i]
}

, but the row number of m in real world is usually big. Is there any effient way to do this?

like image 582
cogitovita Avatar asked Nov 21 '13 09:11

cogitovita


2 Answers

m[rep(1:nrow(m), times = v), ]
#      [,1] [,2]
# [1,]    1    4
# [2,]    1    4
# [3,]    1    4
# [4,]    2    5
# [5,]    3    6
# [6,]    3    6
like image 133
Julius Vainora Avatar answered Oct 21 '22 08:10

Julius Vainora


> m <- matrix(1:25, ncol=5)

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

> apply(m, 2, function(c) rep(c,v))

      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    6   11   16   21
 [2,]    2    7   12   17   22
 [3,]    2    7   12   17   22
 [4,]    3    8   13   18   23
 [5,]    3    8   13   18   23
 [6,]    3    8   13   18   23
 [7,]    4    9   14   19   24
 [8,]    4    9   14   19   24
 [9,]    4    9   14   19   24
[10,]    4    9   14   19   24
[11,]    5   10   15   20   25
[12,]    5   10   15   20   25
[13,]    5   10   15   20   25
[14,]    5   10   15   20   25
[15,]    5   10   15   20   25
like image 41
Raffael Avatar answered Oct 21 '22 08:10

Raffael