Group integer vector into consecutive runs
aggregate, r
Solution
Here's a brief answer using aggregate....
runs <- cumsum( c(0, diff(my.data$V2) > 1) )
aggregate(V2 ~ runs + V1, my.data, range)[,-1]
V1 V2.1 V2.2
1 1 2 5
2 1 7 11
3 1 13 13
4 2 4 9
5 2 11 13
6 3 1 6
7 3 101 105
Problem
I have two vectors of integer. I would like to identify the intervals of consecutive integer sequences presented in the second vector conditioned by the first vector (this vector can be seen as a factor, by which the second vector can be classified into several groups). Here I present a dummy for my problem. The data, in one group (defined by the first vector) of the second vector, the integers monotonically increase. ``` my.data <- data.frame( V1=c(rep(1, 10), rep(2, 9), rep(3,11)), V2=c(seq(2,5), seq(7,11), 13, seq(4, 9), seq(11,13), seq(1, 6), seq(101, 105)) ) ``` What I want: - output the begin and end of the interval - here, group in the first column, the beginning integer in the second, the end integer in the third. Expected results: ``` 1, 2, 5 \n 1, 7, 11 \n 1, 13, 13 \n 2, 4, 9 \n 2, 11, 13 \n 3, 1, 6 \n 3, 101, 105 \n ```