Calculate days since last event in R

后端 未结 5 869
别那么骄傲
别那么骄傲 2020-12-17 10:04

My question involves how to calculate the number of days since an event last that occurred in R. Below is a minimal example of the data:

df <- data.frame         


        
5条回答
  •  情书的邮戳
    2020-12-17 10:51

    I'm way late to the party, but I used tidyr::fill to make this easier. You essentially convert your non-events to missing values, then use fill to fill the NAs in with the last event, then subtract the current date from the last event.

    I've tested this with a integer date column, so it might need some tweaking for a Date-type date column (especially the use of NA_integer_. I'm not sure what the underlying type is for Date objects; I'm guessing NA_real_.)

    df %>%
      mutate(
        event = as.logical(event),
        last_event = if_else(event, true = date, false = NA_integer_)) %>%
      fill(last_event) %>%
      mutate(event_age = date - last_event)
    

提交回复
热议问题