time series - Calculate first difference by group in R -


i wondering if me calculate first difference of score group. know should simple process reason i'm having trouble doing it..... yikes

here's example data frame:

score <- c(10,30,14,20,6)  group <- c(rep(1001,2),rep(1005,3))  df <- data.frame(score,group)  > df    score group 1    10  1001 2    30  1001 3    14  1005 4    20  1005 5     6  1005 

and here's output looking for.

1   na 2   20 3   na   4    6 5  -14 

thanks in advance.

this 1 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 - more efficient larger data.frames

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

Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -