Skip to content

Count number of consecutive zeros by group

3 messages · PIKAL Petr, arun

#
Hi

Another option is sapply/split/sum construction

with(data, sapply(split(x, ID), function(x) sum(x==0)))

Regards
Petr
#
I think this gives a different result than the one OP asked for:

df1 <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), x = c(1, 0, 
0, 1, 0, 0, 0, 1, 2, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0)), .Names = c("ID", 
"x"), row.names = c(NA, -22L), class = "data.frame")

with(df1, sapply(split(x, ID), function(x) sum(x==0)))

with(df1,tapply(x,list(ID),function(y) {rl <- rle(!y); max(c(0,rl$lengths[rl$values]))}))


A.K.
On Friday, November 1, 2013 6:01 AM, PIKAL Petr <petr.pikal at precheza.cz> wrote:
Hi

Another option is sapply/split/sum construction

with(data, sapply(split(x, ID), function(x) sum(x==0)))

Regards
Petr
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
#
Hi

Yes you are right. This gives number of zeroes not max number of consecutive zeroes.

Regards
Petr