Skip to content
Prev 383098 / 398502 Next

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

Hi Nevil,
It's a nasty piece of work, but:

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")))
M
reprow<-function(x)
 return(matrix(rep(x,x[length(x)]),nrow=x[length(x)],byrow=TRUE))
toseq<-function(x) return(1:x)
j<-unlist(sapply(M[,"k"],toseq))
Mlist<-apply(M,1,reprow)
Mlist
newM<-Mlist[[1]]
for(i in 2:length(Mlist)) newM<-rbind(newM,Mlist[[i]])
newM
newM<-cbind(newM,j)
colnames(newM)<-c(colnames(M),"j")
newM

Jim
On Wed, Apr 1, 2020 at 1:43 PM nevil amos <nevil.amos at gmail.com> wrote: