Calculate differences between rows faster than a for loop?

前端 未结 3 785
情书的邮戳
情书的邮戳 2020-12-18 08:32

I have a data set that looks like this:

ID   |   DATE    | SCORE
-------------------------
123  |  1/15/10  |  10
123  |  1/1/10   |  15
124  |  3/5/10   |           


        
3条回答
  •  甜味超标
    2020-12-18 09:25

    In the case where you need a more complex formula, you can use aggregate:

    a <- aggregate(date ~ id, data=data, FUN=function(x) c(NA,diff(x)))
    data$dayssincelast <- c(t(a[-1]), recursive=TRUE) # Remove 'id' column
    

    The same sort order applies here as in @nograpes answer.

提交回复
热议问题