- A+

Category：Languages

I'm trying to calculate a sequence of win streaks for a binary vector. Given a vector

`set.seed(2) x <- sample(c(0,1), 10, replace = TRUE) [1] 0 1 1 0 1 1 0 1 0 1 `

I want to calculate the cumulative sum of ones with a "reset" every time there's a zero. So, in this case, the output of the function should be

`[1] 0 1 2 0 1 2 0 1 0 1 `

What's the easiest way to do this on R?

We can use `ave`

and create a grouping variable with `cumsum`

at every occurrence of 0 in the vector and count the consecutive numbers without 0 in each group.

`ave(x, cumsum(x==0), FUN = seq_along) - 1 #[1] 0 1 2 0 1 2 0 1 0 1 `