# 如何计算R中向量中按顺序排列的相同元素的数量？

x< -c(1,1,1,-1,1,1,1,1,1,1,-1,-1,1,1,-1,-1,-1,-1,-1 ,-1,-1,1) 我希望算法产生一个向量(3,1,6,2,2,7,1) 这意味着3个“1”,1个“-1”,6个“1”等… 我已经开发了以下算法,但它不适用于每个向量x,这可能是我将要有的.

```y<-c(0)
q=0
z=0
w=0
e=1

if (x[1]==1)
{
q<-abs(sum(x[1:(min(which(x < 0))-1)]))
y[e]<-q
k=q+1
z<-abs(sum(x[k:min(which(x < 0))]))
e=e+1
y[e]<-z
k=k+z
r<-matrix(c(which(x < 0)))
w<-matrix(c(which(x > 0)))

while( k<22 )

{

if( all(r<k) )
{
z<-sum(x[k:22])
e=e+1
y[e]<-z
k=k+z
}else
{
z<-abs(sum(x[k:min(r[which(r > k)]-1)]))
e=e+1
y[e]<-z
k=k+z
}

if( all(w<k) )
{
z<-abs(sum(x[k:22]))
e=e+1
y[e]<-z
k=k+z
}else
{z<-abs(sum(x[k:min(w[which(w > k)]-1)]))
e=e+1
y[e]<-z
k=k+z
}

}}```

x< -c(1,1,1,-1,1,1,1,1,1,1,-1,-1,1,1,-1,-1,-1,-1,-1 ,-1,-1,-1)

```rle(x)
#Run Length Encoding
#  lengths: int [1:7] 3 1 6 2 2 7 1
#  values : num [1:7] 1 -1 1 -1 1 -1 1```

```rle(x)\$lengths
#[1] 3 1 6 2 2 7 1```

@clemlaflemme函数和rle之间的效率比较：

```library(microbenchmark)

x <- rep(x,5000)

microbenchmark(clem_shift(),cath_rle(),clem_cumul(),unit="relative")
#Unit: relative
#         expr        min        lq        mean     median         uq        max neval cld
# clem_shift()   1.000000   1.00000   1.0000000   1.000000   1.000000  1.0000000   100  a
#   cath_rle()   1.181513   1.13419   0.8552573   1.095478   1.041918  0.9483564   100  a
# clem_cumul() 325.480391 284.14827 170.1371421 265.160409 241.954976 54.5240969   100   b```