[R] Efficient way to find consecutive integers in vector?

Marc Schwartz marc_schwartz at comcast.net
Thu Dec 20 23:33:54 CET 2007


On Thu, 2007-12-20 at 22:43 +0100, Johannes Graumann wrote:
> Hi all,
> 
> Does anybody have a magic trick handy to isolate directly consecutive
> integers from something like this:
> c(1,2,3,4,7,8,9,10,12,13)
> 
> The result should be, that groups 1-4, 7-10 and 12-13 are consecutive
> integers ...
> 
> Thanks for any hints, Joh

Not fully tested, but here is one possible approach:

> Vec
 [1]  1  2  3  4  7  8  9 10 12 13

Breaks <- c(0, which(diff(Vec) != 1), length(Vec))

> Breaks
[1]  0  4  8 10

> sapply(seq(length(Breaks) - 1), 
         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))

> Vec
 [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))

> Breaks
[1]  0  6 10 13 15

> sapply(seq(length(Breaks) - 1), 
         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



More information about the R-help mailing list