r - Build summary table from matrix -
i have matrix
mdat <- matrix(c(0,1,1,1,0,0,1,1,0,1,1,1,1,0,1,1,1,1,0,1), nrow = 4, ncol = 5, byrow = true) [,1] [,2] [,3] [,4] [,5] [1,] 0 1 1 1 0 [2,] 0 1 1 0 1 [3,] 1 1 1 0 1 [4,] 1 1 1 0 1
and i'm trying build t:
t1 t2 t3 row1 1 2 4 row2 2 2 3 row3 2 5 5 row4 3 1 3 row5 3 5 5 row6 4 1 3 row7 4 5 5
where each row in mdat: t1 shows mdat row number t2 shows mdat column there's first 1 t3 shows mdat column there's last consecutive 1.
therefore
row1 in t [1 2 4] because row 1 in mdat first 1 in column 2 , last consecutive 1 in column 4.
row2 in t [2 2 3] because row 2 in mdat first 1 in column 2 , last consecutive 1 in column 3.
this try:
for (i in 1:4){ (j in 1:5) { if (mdat[i,j]==1) {t[i,1]<-i;t[i,2]<-j; cont<-0; while (mdat[i,j+cont]==1){ cont<-cont+1; t[i,3]<-cont} } } }
here's strategy using apply/rle
richard suggested.
xx<-apply(mdat, 1, function(x) { r <- rle(x) w <- which(r$values==1) l <- r$lengths[w] s <- cumsum(c(0,r$lengths))[w]+1 cbind(start=s,stop=s+l-1) }) do.call(rbind, map(cbind, row=seq_along(xx), xx))
we start finding runs of 1 on each row using "values" property of rle
, calculate start , stop positions using "lengths" property. turn data list of 2 column matrices 1 list item per row of original matrix.
now use map add row number onto matrix , rbind results. seems give data you're after
row start stop [1,] 1 2 4 [2,] 2 2 3 [3,] 2 5 5 [4,] 3 1 3 [5,] 3 5 5 [6,] 4 1 3 [7,] 4 5 5
Comments
Post a Comment