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)
A simple one in base R:
ave(x, cumsum(!x), FUN = cumsum)
#[1] 0 0 1 2 3 0 1 0 1 2 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With