7

我有一系列事件,编码为 A、B 和 C。对于每个元素,我需要计算该元素之前重复了多少次。例如:

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"

我需要从 x 生成列 y。

4

1 回答 1

13

使用rle和的组合sequence

> sequence(rle(x)$lengths)-1
 [1] 0 1 2 0 0 1 0 0 0 0
于 2012-10-15T21:20:39.217 回答