Ryan Sharp
Ryan Sharp

Reputation: 9

Finding max run length of a particular value

I have a vector that I want to analyze for run length. For ease of explanation, it is an unfair coin flip so....100 "H" and "T"....but way more T's than H's

I used

rle(sim) 

to get run lengths.

I used

max(rle(sim)$length) 

to get the maximum run length of the set. However, I only want it for a certain value, say just the H's. How would I do that?

Upvotes: 1

Views: 745

Answers (1)

rld2
rld2

Reputation: 31

 set.seed(100)
 coins <- sample(c("H", "T"), 1000, replace = TRUE)
 rle_coins <- rle(coins)
 max(rle_coins$lengths[rle_coins$values == "H"])

Use tapply to get grouped max:

tapply(rle_coins$lengths, rle_coins$values, max)

Upvotes: 2

Related Questions