[R] Count number of consecutive zeros by group

S Ellison S.Ellison at LGCGroup.com
Thu Oct 31 12:34:32 CET 2013



> -----Original Message-----
> So I want to get the max number of consecutive zeros of variable x for each
> ID. I found rle() to be helpful for this task; so I did:
> 
> FUN <- function(x) {
>   rles <- rle(x == 0)
> }
> consec <- lapply(split(df[,2],df[,1]), FUN)

You're probably better off with tapply and a function that returns what you want. You're probably also better off with a data frame name that isn't a function name, so I'll use dfr instead of df...

dfr<- data.frame(x=rpois(500, 1.5), ID=gl(5,100)) #5 ID groups numbered 1-5, equal size but that doesn't matter for tapply

f2 <-   function(x) {
	max( rle(x == 0)$lengths )
}
with(dfr, tapply(x, ID, f2))


S Ellison


*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list