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

nevil amos nev||@@mo@ @end|ng |rom gm@||@com
Wed Apr 1 03:18:37 CEST 2020


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)[4]<-"j"
print(Mout)

#########################################################

Thanks

Nevil Amos

	[[alternative HTML version deleted]]



More information about the R-help mailing list