R - A subset of a matrix group based on a condition

I am trying to multiply a matrix based on a specific value in a column. But I want my subsets to be in several separate matrices. For example, for example, I have a ccc matrix that

 aaa=c(1,1,1,2,5,1,2,1,1,3,1,1,1,1,1,1,4) bbb=c(4,4,4,4,3,3,3,3,2,2,2,2,3,4,5,6,7) ccc=cbind(aaa,bbb) 

I want a subset using the condition ccc[,1]==1 , and at the same time I want the subset to be split into several matrices, separated by a breakpoint. Gaps are based on runs aaa==1 . To make this clear, I need my results as follows:

 ddd1 aaa bbb [1,] 1 4 [2,] 1 4 [3,] 1 4 ddd2 aaa bbb 1 3 ddd3 aaa bbb [1,] 1 3 [2,] 1 2 ddd4 aaa bbb [1,] 1 2 [2,] 1 2 [3,] 1 3 [4,] 1 4 [5,] 1 5 [6,] 1 6 

ddd1,..,ddd4 are subset matrices. I hope I made it clear. Any suggestion how to do this?

+6
source share
1 answer

Use split and cumsum :

 ccc <- data.frame(ccc) split(ccc[ccc$aaa==1,], cumsum(ccc$aaa!=1)[ccc$aaa==1]) #$`0` # aaa bbb #1 1 4 #2 1 4 #3 1 4 # #$`2` # aaa bbb #6 1 3 # #$`3` # aaa bbb #8 1 3 #9 1 2 # #$`4` # aaa bbb #11 1 2 #12 1 2 #13 1 3 #14 1 4 #15 1 5 #16 1 6 
+5
source

Source: https://habr.com/ru/post/986614/


All Articles