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?
Although sometimes claimed as a winning streak by those unaccustomed to winning, simply winning two games in a row is most definitely not a win streak. In sports, it can be applied to teams, and individuals.
[ kwin-too-puhl, -tyoo-, -tuhp-uhl, kwin-too-puhl, -tyoo- ] SHOW IPA.
What is the longest winning streak? 33 consecutive wins is the record for the longest winning streak, hold by the Los Angeles Lakers 1971-1972: a record that a record that has been running for 40 years.
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
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