我试图弄清楚当事件存储为数据框中的一列日期时如何获取连续事件之间的时间。
sampledf=structure(list(cust = c(1L, 1L, 1L, 1L), date = structure(c(9862,
9879, 10075, 10207), class = "Date")), .Names = c("cust", "date"
), row.names = c(NA, -4L), class = "data.frame")
我可以得到答案
as.numeric(rev(rev(difftime(c(sampledf$date[-1],0),sampledf$date))[-1]))
# [1] 17 196 132
但它真的很丑。除其他外,我只知道如何排除向量中的第一项,但不知道最后一项,所以我必须两次 rev() 才能删除最后一个值。
有没有更好的办法?
顺便说一句,我将使用 ddply 对每个客户 ID 的更大数据集执行此操作,因此该解决方案需要使用 ddply。
library(plyr)
ddply(sampledf,
c("cust"),
summarize,
daysBetween = as.numeric(rev(rev(difftime(c(date[-1],0),date))[-1]))
)
谢谢!