MaThorn
MaThorn

Reputation: 31

Count number of sequences in a vector in 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

Upvotes: 3

Views: 1097

Answers (1)

Roland
Roland

Reputation: 132706

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.

Upvotes: 2

Related Questions