R: counting consecutive days

后端 未结 1 1582
长发绾君心
长发绾君心 2021-02-14 16:48

I am having trouble solving this one, I have a DF with a list of count data. For example something like this:

 DATE        TIME     ID
 2014-02-14  15:02    1
 2         


        
1条回答
  •  粉色の甜心
    2021-02-14 17:54

    We can use dplyr. First, convert your data in proper date format:

    z$date <- as.Date(as.character(z$date), format = "%d-%m-%y")
    

    Now the function:

    library(dplyr)
    runchecker <- function(data, days){
      data %>% arrange(date) %>%
               group_by(ID) %>%
               mutate(diff = c(0, diff(date)),
                      periodID = 1 + cumsum(diff > days)) %>%
               group_by(ID, periodID) %>%
               summarise(days = last(date) - first(date))
    }
    

    and call it on your data:

    runchecker(data, 1)
    Source: local data frame [4 x 3]
    Groups: ID [?]
    
         ID periodID   days
      (int)    (dbl) (dfft)
    1     1        1 0 days
    2     2        1 3 days
    3     3        1 0 days
    4     4        1 0 days
    

    NB your data has very few date changes or gaps, maybe include a better data set for testing?

    0 讨论(0)
提交回复
热议问题