Calculate difference between values in consecutive rows by group

后端 未结 3 813
遥遥无期
遥遥无期 2020-11-22 10:14

This is a my df (data.frame):

group value
1     10
1     20
1     25
2     5
2     10
2     15 

I need to calculate difference

3条回答
  •  星月不相逢
    2020-11-22 10:36

    try this with tapply

    df$diff<-as.vector(unlist(tapply(df$value,df$group,FUN=function(x){ return (c(NA,diff(x)))})))
    

提交回复
热议问题