CephBirk
CephBirk

Reputation: 6710

Calculate number of sequential identical elements in a vector in R

If I have the vector c(1,1,2,5,3,5,6,6,6,6,3,2,7,3,4,4,4,2,2,1) how can I calculate the number of sequential identical elements? The result I'm looking for would be c(2,1,1,1,1,4,1,1,1,1,3,2,1). I'd prefer to avoid for loops please since my application of this concept is for a very long vector!

Upvotes: 0

Views: 106

Answers (1)

blakeoft
blakeoft

Reputation: 2400

Try this

rle(x)$lengths

I imagine that it is pretty efficient because it's a base function.

Upvotes: 3

Related Questions