Create matrix row-index which increments when rowsum > 100, and following row

  • A+
Category:Languages

I have a matrix:

mat <- matrix(c(2,11,3,1,2,4,55,65,12,4,6,6,7,9,3,23,16,77,5,5,7),ncol = 3, byrow = TRUE)       [,1] [,2] [,3] [1,]    2   11    3 [2,]    1    2    4 [3,]   55   65   12 [4,]    4    6    6 [5,]    7    9    3 [6,]   23   16   77 [7,]    5    5    7 

I want to add a column with rows index. This index will starts at 1 and repeats the same index, until it arrived to a row where the rowsums is > 100 to move to the next value.

  Indx[,2][,3][,4] [1,] 1  2 11  3 [2,] 1  1  2  4 [3,] 2 55 65 12 [4,] 3  4  6  6 [5,] 3  7  9  3 [6,] 4 23 16 77 [7,] 5  5  5  7 

 


Using rle:

matRle <- rle(rowSums(mat) > 100)$lengths  cbind(rep(seq(length(matRle)), matRle), mat) #      [,1] [,2] [,3] [,4] # [1,]    1    2   11    3 # [2,]    1    1    2    4 # [3,]    2   55   65   12 # [4,]    3    4    6    6 # [5,]    3    7    9    3 # [6,]    4   23   16   77 # [7,]    5    5    5    7 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: