R how to identify distance of last occurrence

后端 未结 3 2039
耶瑟儿~
耶瑟儿~ 2021-01-18 08:31

I want to calculate how long its been since something occurred.

Given the following, you can see that the light is on some of the time, but not all of the time. I wa

3条回答
  •  没有蜡笔的小新
    2021-01-18 09:15

    I would suggest creating a grouping column based on when there is a switch from FALSE to TRUE:

    # create group column
    d[c(light), group := cumsum(light)]
    d[is.na(group), group:=0L]
    d[, group := cumsum(group)]
    d
    

    Then simply tally by group, using cumsum and negating light:

    d[, distance := cumsum(!light), by=group]
    
    # remove the group column for cleanliness
    d[, group := NULL]
    

    Results:

    d
    
             date light distance
    1: 2013-06-01  TRUE        0
    2: 2013-06-02 FALSE        1
    3: 2013-06-03 FALSE        2
    4: 2013-06-04  TRUE        0
    5: 2013-06-05  TRUE        0
    6: 2013-06-06 FALSE        1
    7: 2013-06-07 FALSE        2
    8: 2013-06-08  TRUE        0
    

    I added a few rows

提交回复
热议问题