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
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]