Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

indexing

r

matrix

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
like image 623
user10231391 Avatar asked Aug 15 '18 21:08

user10231391


2 Answers

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
like image 96
zx8754 Avatar answered Oct 12 '22 01:10

zx8754


A solution using dplyr.

library(dplyr)

mat2 <- mat %>%
  as.data.frame() %>%
  mutate(Indx = cumsum(rowSums(dat) > 100 | lag(rowSums(dat) > 100, default = TRUE))) %>%
  select(Indx, paste0("V", 1:ncol(mat))) %>%
  as.matrix()
mat2
#      Indx V1 V2 V3
# [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
like image 33
www Avatar answered Oct 12 '22 02:10

www