Count how many times an element is repeated in sequence (in R)

I have a sequence of events encoded as A, B, and C. For each element, I need to count how many times this element has been repeated before. For example:

x<-c('A','A','A','B','C','C','A','B','A','C') y<-c(0,1,2,0,0,1,0,0,0,0) cbind(x,y) xy [1,] "A" "0" [2,] "A" "1" [3,] "A" "2" [4,] "B" "0" [5,] "C" "0" [6,] "C" "1" [7,] "A" "0" [8,] "B" "0" [9,] "A" "0" [10,] "C" "0" 

I need to create a column y from x.

+7
source share
1 answer

Use a combination of rle and sequence :

 > sequence(rle(x)$lengths)-1 [1] 0 1 2 0 0 1 0 0 0 0 
+13
source

All Articles