evian_bottle
evian_bottle

Reputation: 77

Find the longest sequence of the same value in vector, R

Does anyone have an idea of how to determine the longest repetition of any value in a vector?

So for example I have the following vector:

sample <- c(1,1,1,2,3,2,1,2,3,4,5,6,6,6,6,4,3,2)

The expected output should be 4 times (as there are four consecutive 6 in the vector). So I am interested in finding out the length of maximal repetition of one same value.

Upvotes: 1

Views: 945

Answers (2)

s_baldur
s_baldur

Reputation: 33548

with rle()

max(rle(sample)$lengths)

Upvotes: 2

akrun
akrun

Reputation: 887611

We can use rle

with(rle(sample), max(lengths))
#[1] 4

If we need it for each unique value,

with(rle(sample), tapply(lengths, values, FUN = max))
# 1 2 3 4 5 6 
#3 1 1 1 1 4 

Upvotes: 1

Related Questions