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 TRUE
s 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)
There's always interesting ways to employ
cumsum
to do this sort of counter: