shadow.
shadow.

Reputation: 9

Counting specific sets of repeats

I am having to write code in r where I have to count the number of times a specific set of numbers within a vector are repeated one after another.

For example, in the following set of numbers, I would want to count the number of times a number was repeated after itself, such as 2,2 and 4,4, or even repeating after itself 3 times in a row such as 1,1,1 or 3,3,3, not counting the number of times an individual number has occurred throughout the set.

5, 3, 2, 2, 4, 1, 4, 4, 6, 1, 3, 2, 1, 4, 3, 1, 6, 4, 5, 5, 3, 4, 3, 4, 4, 5, 6, 6, 2, 4, 6, 1, 1, 1, 2, 2, 4, 3, 3, 3, 1, 3, 5, 1, 5, 2, 2, 6, 5, 6, 3

Upvotes: 1

Views: 34

Answers (1)

Sotos
Sotos

Reputation: 51592

You can use rle to find repeated consecutive values. For example,

i1 <- rle(x)
setNames(i1$lengths[i1$lengths > 1], paste0('value:', i1$values[i1$lengths > 1]))
#value:2 value:4 value:5 value:4 value:6 value:1 value:2 value:3 value:2 
#      2       2       2       2       2       3       2       3       2 

DATA

dput(x)
c(5, 3, 2, 2, 4, 1, 4, 4, 6, 1, 3, 2, 1, 4, 3, 1, 6, 4, 5, 5, 
3, 4, 3, 4, 4, 5, 6, 6, 2, 4, 6, 1, 1, 1, 2, 2, 4, 3, 3, 3, 1, 
3, 5, 1, 5, 2, 2, 6, 5, 6, 3)

Upvotes: 2

Related Questions