# [R] repeat rows of matrix by number (k) in one colummatrix adding column j with values 1:k

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Wed Apr 1 03:33:10 CEST 2020

```False premise: rep works fine

Mout2 <- cbind(M[ rep(seq.int(nrow(M)),M[,"k"]), c("x","y","z")],unlist(lapply(M[,"k"],seq.int)))

On March 31, 2020 6:18:37 PM PDT, nevil amos <nevil.amos using gmail.com> wrote:
>Hi
>
>I can achieve this using two for loops but it is slow  I need to do
>this on
>many matrices with tens of millions of rows of x,y,z and k
>
>What is a faster method to achieve this, I cannot use rep as j changes
>in
>each row of the new matrix
>###############################################
>M<-matrix(c(1,2,3,4,1,2,3,4,1,2,3,4, 2, 1, 3, 2
>), 4,4, dimnames = list(NULL, c("x", "y", "z","k")))
>
>Print(M)
>#Create matrix (Mout) in this case 8 rows with x,y,z in each row of M
>#repeated k times with column j numbered from 1:k
># ! can do with nested loops but this is very slow ( example below)
>#How do I acheive this quickly without loops?
>Mout<-NULL
>
>for(i in 1:nrow(M)){
>  a=M[i,c("x","y","z")]
>  for (j in 1:M[i,"k"]){
>    b=c(a,j)
>    Mout<-rbind(Mout,b)
>    }
>}
>colnames(Mout)<-"j"
>print(Mout)
>
>#########################################################
>
>Thanks
>
>Nevil Amos
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help