Count how many times the element is repeated in a sequence (in R)
r, sequence
Solution
Use a combination of `rle` and `sequence`:
> sequence(rle(x)$lengths)-1
[1] 0 1 2 0 0 1 0 0 0 0
Problem
I have a sequence of events, coded as A,B, and C. For each element I need to count how many times this element was 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) x y [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 generate column y from x.