How to find the indices where there are n consecutive zeroes in a row

前端 未结 4 1101
逝去的感伤
逝去的感伤 2020-12-19 02:02

Suppose I have this data:

  x = c(14,14, 6,  7 ,14 , 0 ,0  ,0 , 0,  0,  0 , 0 , 0,  0 , 0 , 0 , 0,  9  ,1 , 3  ,8  ,9 ,15,  9 , 8, 13,  8,  4 , 6 , 7 ,10 ,13         


        
4条回答
  •  失恋的感觉
    2020-12-19 02:50

    Starts = which(diff(x == 0) == 1) + 1
    Ends   = which(diff(x == 0) == -1)
    if(length(Ends) < length(Starts)) {
        Ends = c(Ends, length(x)) }
    
    Starts
    [1]  6 34 72
    Ends
    [1] 17 58 89
    

    This works for your test data, but allows any sequence of zeros, including short ones. To insure that you get sequences of length at least n, add:

    n=3
    Long = which((Ends - Starts) >= n)
    Starts = Starts[Long]
    Ends = Ends[Long]
    

提交回复
热议问题