看看下面的MWE:
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
我希望按ID分组,自上次活动以来的天数。我的问题类似于this one。只是,我希望按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
我尝试了以下内容:
我尝试使用ddply函数中链接中提出的步骤,如下所示。但这似乎没有起到作用。
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])
我希望有人知道如何做到这一点。