Finding the start and stop indices in sequence in

2019-05-26 01:11发布

问题:

Suppose I have the sequence:

x = c( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0)

Is there an elegant way in R to return the start and stop indices of each sequence of 1s?

The answer should be a 2 column array with nRows = number of sequences of 1s:

startIndx = [ 1, 5, 7 ]
stopIndex = [ 2, 5, 9 ]

Thanks.

BSL

回答1:

Assuming your vector consists of 0 and 1 values:

which(diff(c(0L, x)) == 1L)
#[1] 1 5 7
which(diff(c(x, 0L)) == -1L)
#[1] 2 5 9

Otherwise you'd need something like x <- x == 1L first.



回答2:

Elegant way is

y <- which(x==1)
startIndx <- y[!(y-1) %in% y]
stopIndex <- y[!(y+1) %in% y]
rbind(startIndx, stopIndex)
#          [,1] [,2] [,3]
#startIndx    1    5    7
#stopIndex    2    5    9


回答3:

What about this? [editted version according to suggestion of alexis_laz]

library(cgwtools)
res <- seqle(which(as.logical(x)))
rbind(res$values, res$values + res$lengths - 1)
     [,1] [,2] [,3]
[1,]    1    5    7
[2,]    2    5    9


回答4:

How about this:

startIndx<-rev(length(x)-cumsum(rle(rev(x))$lengths)[rle(rev(x))$values==1]+1)
stopIndex<-cumsum(rle(x)$lengths)[rle(x)$values==1]


回答5:

Try this:

y = rle(x)

stopIndex  = with(y, cumsum(lengths)[values==1])
startIndex = stopIndex - with(y, lengths[values==1]) + 1

#> stopIndex
#[1] 2 5 9
#> startIndex
#[1] 1 5 7