Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of win streaks [duplicate]

Tags:

r

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?

like image 547
user3294195 Avatar asked Aug 13 '18 01:08

user3294195


People also ask

Is 2 games a winning streak?

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.

What do you call five wins in a row?

[ kwin-too-puhl, -tyoo-, -tuhp-uhl, kwin-too-puhl, -tyoo- ] SHOW IPA.

What is the longest win streak?

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.


1 Answers

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
like image 142
Ronak Shah Avatar answered Nov 09 '22 23:11

Ronak Shah