Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of sequences in a vector in r

Tags:

r

New to R and I have a vector that looks like data<- c(1, 2, 3, 9, 10, 11, 12, 29, 30, 31, 32, 33, 34). I want to count the number of sequences of consecutive values. I.e. 1, 2, 3 would be one count, 9, 10, 11, 12 another, and then 29, 30, 31, 32, 33, and 34, for a total count of 3.

I am currently trying to use this loop which would replace all of the sequential values except for the last with NA (and then I could remove the NAs and count):

data<- c(1, 2, 3, 9, 10, 11, 12, 29, 30, 31, 32, 33, 34)
event_detect<- function (data) {
    for (i in 1:length(data)){
        if (data[(i+1)] == data[i]+1){
            data[(i)]<-NA
        }
    }
}

but this returns a "missing value where TRUE/FALSE needed" error. I think this can be achieved without a loop, but I'm having trouble finding a solution. I know rle can do this for runs of equal values, so something like rle for values that increase by 1.

Thanks for your help

like image 557
MaThorn Avatar asked Feb 01 '26 08:02

MaThorn


1 Answers

We count the number of differences that are not one and add one to that number:

sum(diff(data) != 1) + 1

This utitilizes that R coerces logical values to numeric values in arithmetic operations.

like image 106
Roland Avatar answered Feb 03 '26 23:02

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!