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

前端 未结 4 1107
逝去的感伤
逝去的感伤 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条回答
  •  猫巷女王i
    2020-12-19 02:40

    By using dplyr , get the diff then if the diff not equal to 0 , they are not belong to same group , after cumsum we get the grouid

    library(dplyr)
    df=data.frame('x'=x,rownumber=seq(length(x)))
    df$Groupid=cumsum(c(0,diff(df$x==0))!=0)
    df%>%group_by(Groupid)%>%summarize(start=first(rownumber),end=last(rownumber),number=first(x),size=n())%>%filter(number==0&size>=3)
    # A tibble: 3 x 5
      Groupid start   end number  size
             
    1       1     6    17      0    12
    2       3    34    58      0    25
    3       5    72    89      0    18
    

提交回复
热议问题