问题
Have a look at the MWE below:
df <- data.frame(date=as.Date(c("06/07/2000","15/09/2000","15/10/2000","03/01/2001","17/03/2001","23/05/2001","26/08/2001"), "%d/%m/%Y"),
event=c(0,0,1,0,1,1,0))
id date event
01 2000-07-06 0
01 2000-09-15 0
01 2000-10-15 1
01 2001-01-03 0
02 2001-03-17 1
02 2001-05-23 1
02 2001-08-26 0
02 2001-08-28 0
03 2001-08-29 1
03 2001-09-05 1
03 2001-09-30 0
03 2001-10-12 1
I want, grouped per ID, the number of days since the last event. My question is similar to this one. Only, I want the result grouped per ID:
id date event tae
01 2000-07-06 0 NA
01 2000-09-15 0 NA
01 2000-10-15 1 0
01 2001-01-03 0 80
02 2001-03-17 1 0
02 2001-05-23 1 67
02 2001-08-26 0 95
02 2001-08-28 0 97
03 2001-08-29 1 0
03 2001-09-05 1 7
03 2001-09-30 0 25
03 2001-10-12 1 38
I tried the following:
I tried using the steps proposed in the link in a ddply function as below. But this does not seem to do the job.
ddply(df, .(id), transform, last_event_index <- cumsum(df$event) + 1))
ddply(df, .(id), transform, last_event_index <- c(1, last_event_index[1:length(last_event_index) - 1]))
df<- ddply(operationaltemp, .(id), transform, last_event_date = df[which(df$event==1), "date"])[df$last_event_index])
I hope somebody knows how this can be done.
来源:https://stackoverflow.com/questions/33958035/calculate-days-since-last-event-grouped-per-id-in-r