Count largest number of consecutive zeros in a vector using a vectorized function

Viewed 65

I'd like to build a function that takes a vector as an argument and returns the largest number of consecutive zeros. For instance:

a <- c(0,0,1,1,0)
b <- c(0,1,3,10,0,0,0)
x <- count_max_consecutive_zeros(a)
y <- count_max_consecutive_zeros(b)

Should result in x=2 and y=3. I could go for the obvious solution and make a loop:

count_max_consecutive_zeros <- function(x) {
  max_count <- 0
  current_count <- 0
  for (i in 1:length(x) {
   if(x[i] == 0) {
     current_count = current_count + 1
  } else {
    if(current_count > max_count) {
      max_count <- current_count
    }
    current_count <- 0
  }
}

This solution is fine for short vectors, however I'll have to use this function thousands of times on vectors that are tens of thousands of entries long, so I'm afraid I'll run into performance issues. Is there a vectorized function equivalent to count_max_consecutive_zeros?

2 Answers

You can use rle and max to count largest number of consecutive zeros.

x <- rle(a==0)
max(x$lengths[x$values == TRUE])
#[1] 2

An option with rleid

library(data.table)
max(tapply(a[a==0], rleid(a)[a == 0], FUN = length))
#[1] 2
Related