Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

sequence

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.

like image 535
Andrey Chetverikov Avatar asked Oct 15 '12 21:10

Andrey Chetverikov


1 Answers

Use a combination of rle and sequence:

> sequence(rle(x)$lengths)-1
 [1] 0 1 2 0 0 1 0 0 0 0
like image 82
Joshua Ulrich Avatar answered Sep 24 '22 12:09

Joshua Ulrich