Count consecutive TRUE values within each block se

2020-03-19 02:32发布

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)

标签: r
7条回答
何必那么认真
2楼-- · 2020-03-19 03:27

There's always interesting ways to employ cumsum to do this sort of counter:

x[x] <- ave(x[x], cumsum(!x)[x], FUN=seq_along)
x
# [1] 0 0 1 2 3 0 1 0 1 2 0
查看更多
登录 后发表回答