Count the number of consecutive occurrences in a vector

Viewed 124

I have the following vector:

vec <- c(28, 44, 45, 46, 47, 48, 61, 62, 70, 71, 82, 83, 104, 105, 111, 115, 125, 136, 137, 138, 146, 147, 158, 159, 160, 185, 186, 187, 188, 189, 190, 191, 192, 193, 209, 263, 264, 265, 266, 267, 268, 280, 283, 284, 308, 309, 318, 319, 324, 333, 334, 335, 347, 354)

Now I would like to get the number of consecutive occurrences in the vector of the minimum length two. So here this would be valid for the following cases:

44, 45, 46, 47, 48
61, 62
70, 71
82, 83
104, 105
136, 137, 138
146, 147
158, 159, 160
185, 186, 187, 188, 189, 190, 191, 192, 193
263, 264, 265, 266, 267, 268
283, 284
308, 309
318, 319
333, 334, 335

So there are 14 times cases of consecutive numbers, and I just need the integer 14 as output.

Anybody with an idea how to do that?

4 Answers

We can use rle and diff functions :

a=rle(diff(vec))
sum(a$values==1)

diff and split will help

vec2 <- split(vec, cumsum(c(1, diff(vec) != 1)))
vec2[(sapply(vec2, function(x) length(x))>1)]

$`2`
[1] 44 45 46 47 48

$`3`
[1] 61 62

$`4`
[1] 70 71

$`5`
[1] 82 83

$`6`
[1] 104 105

$`10`
[1] 136 137 138

$`11`
[1] 146 147

$`12`
[1] 158 159 160

$`13`
[1] 185 186 187 188 189 190 191 192 193

$`15`
[1] 263 264 265 266 267 268

$`17`
[1] 283 284

$`18`
[1] 308 309

$`19`
[1] 318 319

$`21`
[1] 333 334 335

Brut force :

var <- sort(var)
nconsecutive <- 0
p <- length(var)-1
for (i in 1:p){
    if((var[i + 1] - var[i]) == 1){
        consecutive <- consecutive + 1
    }else{
        # If at least one consecutive number
        if(consecutive > 0){
        # when no more consecutive numbers add one to your increment
            nconsecutive = nconsecutive + 1
        }
        # Re set to 0 your increment
        consecutive <- 0
    }
}

Here's another base R one-liner using tapply -

sum(tapply(vec, cumsum(c(TRUE, diff(vec) != 1)), length) > 1)
#[1] 14
Related