Calculate days since last event in R

后端 未结 5 862
别那么骄傲
别那么骄傲 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 11:04

    Old question, but I was experimenting with rolling joins and found this interesting.

    library(data.table)
    setDT(df)
    setkey(df, date)
    
    # rolling self-join to attach last event time
    df = df[event == 1, .(lastevent = date), key = date][df, roll = TRUE]
    
    # find difference between record and previous event == 1 record
    df[, tae := difftime(lastevent, shift(lastevent, 1L, "lag"), unit = "days")]
    
    # difftime for simple case between date and joint on previous event
    df[event == 0, tae:= difftime(date, lastevent, unit = "days")]
    
    > df
             date  lastevent event      tae
    1: 2000-07-06            0  NA days
    2: 2000-09-15            0  NA days
    3: 2000-10-15 2000-10-15     1  NA days
    4: 2001-01-03 2000-10-15     0  80 days
    5: 2001-03-17 2001-03-17     1 153 days
    6: 2001-05-23 2001-05-23     1  67 days
    7: 2001-08-26 2001-05-23     0  95 days
    

提交回复
热议问题