Calculate first difference by group in R

后端 未结 4 1566
野的像风
野的像风 2020-12-18 11:54

I was wondering if someone could help me calculate the first difference of a score by group. I know it should be a simple process but for some reason I\'m having trouble doi

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 12:20

    This is one way using base R

    df$diff <- unlist(by(df$score , list(df$group) , function(i) c(NA,diff(i))))
    

    or

    df$diff <- ave(df$score , df$group , FUN=function(i) c(NA,diff(i)))
    


    or using data.table - this will be more efficient for larger data.frames

    library(data.table)
    dt <- data.table(df)
    setkey(dt,group)
    dt[,diff:=c(NA,diff(score)),by=group]
    

提交回复
热议问题