Lyndz
Lyndz

Reputation: 423

How to count consecutive occurrence below a threshold in R

I have the following data:

> dput(s1[1:10,])

structure(list(V1 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), V2 = c(0, 
0.55, 0.9, 3.125, 5, 19.96666667, 12.25, 35.15, 5.4, 58.58)), 
na.action = structure(260:270, .Names = c("260", 
"261", "262", "263", "264", "265", "266", "267", "268", "269", 
"270"), class = "omit"), row.names = c("33", "317", "6", 
"202","250", "185", "28", "251", "218", "116"), class = 
"data.frame")

I would like to count the number of consecutive occurrences when V2 (the second column) is below 1 for at least 3 consecutive time steps.

So in the above example, the answer should 1.

If I resample the above data:

b<-a[sample(1:nrow(a),replace=T),]
dput(b)

structure(list(V1 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), V2 = c(5, 
35.15, 0.55, 19.96666667, 0.55, 19.96666667, 0.55, 3.125, 0.9, 
0.55)), na.action = structure(260:270, .Names = c("260", 
"261","262", "263", "264", "265", "266", "267", "268", "269", 
"270"), class = "omit"), row.names = c("250", "251", "317", 
"185","317.1", "185.1", "317.2", "202", "6", "317.3"), class = 
"data.frame")

Here, the answer should be 0.

How can I get these values with a one line command in R? is this possible?

I'll appreciate any help.

Upvotes: 2

Views: 619

Answers (2)

akrun
akrun

Reputation: 886938

Here is an option with rleid from data.table

library(data.table)
nrow(setDT(s1)[, if(all(V2 < 1)) .N, rleid(V2 < 1)])
#[1] 1

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

Using rle :

with(rle(s1$V2 < 1), sum(lengths[values] >= 3))
#[1] 1

Upvotes: 2

Related Questions