Skip to content
Prev 132584 / 398506 Next

Efficient way to find consecutive integers in vector?

On Thu, 2007-12-20 at 22:43 +0100, Johannes Graumann wrote:
Not fully tested, but here is one possible approach:
[1]  1  2  3  4  7  8  9 10 12 13

Breaks <- c(0, which(diff(Vec) != 1), length(Vec))
[1]  0  4  8 10
function(i) Vec[(Breaks[i] + 1):Breaks[i+1]])
[[1]]
[1] 1 2 3 4

[[2]]
[1]  7  8  9 10

[[3]]
[1] 12 13



For a quick test, I tried it on another vector:


set.seed(1)
Vec <- sort(sample(20, 15))
[1]  1  2  3  4  5  6  8  9 10 11 14 15 16 19 20

Breaks <- c(0, which(diff(Vec) != 1), length(Vec))
[1]  0  6 10 13 15
function(i) Vec[(Breaks[i] + 1):Breaks[i+1]])
[[1]]
[1] 1 2 3 4 5 6

[[2]]
[1]  8  9 10 11

[[3]]
[1] 14 15 16

[[4]]
[1] 19 20


HTH,

Marc Schwartz