R how to identify distance of last occurrence

后端 未结 3 2055
耶瑟儿~
耶瑟儿~ 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:06

    This should do it:

    d[, distance := 1:.N - 1, by = cumsum(light)]
    

    or this:

    d[, distance := .I - .I[1], by = cumsum(light)]
    

    And if you want to actually count number of days as opposed to row-distance, you could use:

    d[, distance := as.numeric(as.POSIXct(date, format = "%m/%d/%Y") -
                               as.POSIXct(date[1], format = "%m/%d/%Y"),
                               units = 'days'),
        by = cumsum(light)]
    

提交回复
热议问题