Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count consecutive TRUE values within each block separately [duplicate]

Tags:

r

Similar questions have been asked, and I've been trying to cobble the answers (rle, cumsum, etc.) together from various ones but it's taking me hours and I'm still not getting there.

I have a data set with a column containing TRUE / FALSE values only, e.g.:

x <- c(FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE)

For each set of continuous TRUE values, I want to count the number of TRUEs in that set. The FALSE values can be ignored, i.e. I want an output for the above data that looks like this:

x2 <- c(0, 0, 1, 2, 3, 0, 1, 0, 1, 2, 0)
like image 570
Winston Avatar asked Jan 31 '18 21:01

Winston


1 Answers

A simple one in base R:

ave(x, cumsum(!x), FUN = cumsum)

#[1] 0 0 1 2 3 0 1 0 1 2 0
like image 120
989 Avatar answered Sep 19 '22 14:09

989