I am trying to subset a matrix based on a specific value in a column. But I want my subsets in a number of separate matrices. For eg, say I have a matrix ccc
which is
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 to subset using a condition which is ccc[,1]==1
and at the same time I want the subset to be divided into several matrices separated by a breaking point. The breaks are based on runs of aaa==1
. To make it clear I need my outputs in the following way,
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
being the subset matrices. I hope I made it clear. Any suggestion how to do it?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With