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?