我有一系列事件,编码为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"
Run Code Online (Sandbox Code Playgroud)
我需要从x生成列y.
Jos*_*ich 13
使用的组合rle和sequence:
> sequence(rle(x)$lengths)-1
[1] 0 1 2 0 0 1 0 0 0 0
Run Code Online (Sandbox Code Playgroud)