Consecutive group number in R

后端 未结 3 1742
暗喜
暗喜 2020-12-22 01:32

This problem is very similar to Consecutive value after column value change in R

So for

SOG <- c(4,4,0,0,0,3,4,5,0,0,1,2,0,0,0)

相关标签:
3条回答
  • 2020-12-22 02:10

    You can try my TrueSeq function from my GitHub-only "SOfun" package.

    Usage would be:

    library(SOfun)
    TrueSeq(as.logical(SOG))
    #  [1] 1 1 0 0 0 2 2 2 0 0 3 3 0 0 0
    

    To get the inverse, just negate the as.logical step:

    TrueSeq(!as.logical(SOG))
    #  [1] 0 0 1 1 1 0 0 0 2 2 0 0 3 3 3
    
    0 讨论(0)
  • 2020-12-22 02:30

    Assuming you mean a "group of SOG" is a set of consecutive non-zero SOG values, i.e. starts with a non-zero SOG value and ends with a non-zero SOG value (not necessarily the same value):

    Trips <- ifelse(SOG>0, cumsum(c(SOG[1]>0, diff(SOG>0)) == 1), 0)
    # [1] 1 1 0 0 0 2 2 2 0 0 3 3 0 0 0
    
    0 讨论(0)
  • 2020-12-22 02:33

    This is one option:

    replace(cumsum(c(SOG[1], abs(diff(SOG))) == SOG & SOG != 0), SOG == 0, 0)
    # [1] 1 1 0 0 0 2 2 2 0 0 3 3 0 0 0
    
    0 讨论(0)
提交回复
热议问题