Calculating Inter-purchase Time in R

后端 未结 1 622
粉色の甜心
粉色の甜心 2020-12-11 09:22

I have the following data frame:

id<-c(1,1,1,3,3,3)
date<-c(\"23-01-07\",\"27-01-07\",\"30-01-07\",\"11-12-07\",\"12-12-07\",\"01-01-08\")
df<-data.         


        
相关标签:
1条回答
  • 2020-12-11 10:02

    You can use plyr:

    library(plyr)
    ddply(df, "id", transform, inter.time = c(0, diff(date2)))
    

    or ave:

    transform(df, inter.time = ave(as.numeric(date2), id,
                                   FUN = function(x)c(0, diff(x))))
    

    Both give

    #   id     date      date2 inter.time
    # 1  1 23-01-07 2007-01-23          0
    # 2  1 27-01-07 2007-01-27          4
    # 3  1 30-01-07 2007-01-30          3
    # 4  3 11-12-07 2007-12-11          0
    # 5  3 12-12-07 2007-12-12          1
    # 6  3 01-01-08 2008-01-01         20
    

    P.S.: you might want to replace these zeroes with NA.

    0 讨论(0)
提交回复
热议问题