[R] Efficient way to repeat rows (or columns) of a matrix?
Talbot Katz
topkatz at msn.com
Thu Mar 1 00:07:21 CET 2007
Hi.
If I have a vector, v_1, and another vector of positive integers, i_1, the
same length as v_1, then rep(v_1,i_1) will repeat v_i[j] exactly i_1[j]
times, like so:
>rep(c(1,2,3),c(3,2,1))
[1] 1 1 1 2 2 3
>
I'd like to do the same sort of thing where I replace v_1 with a matrix, and
the jth row of the matrix is repeated i_1 times.
Obviously, I could do this with for loops, like the following:
>(ma1=matrix(1:6,nrow=2))
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
>vr1=c(2,3)
>rma1=NULL
>for(i in 1:length(vr1)){for(j in 1:vr1[i]){rma1=rbind(rma1,ma1[i,])}}
>rma1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 1 3 5
[3,] 2 4 6
[4,] 2 4 6
[5,] 2 4 6
>
I just thought some of you clever programmers could show me a more efficient
way. (I apologize if this question has come up before and you're tired of
answering it ;-)
Thanks!
-- TMK --
212-460-5430 home
917-656-5351 cell
More information about the R-help
mailing list