Finding the start and stop indices in sequence in R
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 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. Elegant way is y <- which(x==1) startIndx <- y[!(y-1) %in% y] stopIndex <- y[!(y+1) %in% y] rbind(startIndx, stopIndex)