Really frustrated by this. I just want to take difference between rows in a data.table. where dif(n) = value(n) - value(n-1). so, compared to what I have, the results should be shifted by 1 position, and the first position for each "variable" should be NA. i.e. dif should be (NA, 4, -2, NA, 1, -8). The first value for each "variable should be NA because there is no position n-1. Any idea how I can modify the function to accomplish this? Would really like to know how I can do this with rollapplyr for the sake of my own understanding.
Thanks.
data.table:
> dt
       variable value
    1:      xyz     3
    2:      xyz     7
    3:      xyz     5
    4:      abc     9
    5:      abc    10
    6:      abc     2
> dt[,dif := rollapplyr(value, 2, function(x){r <- diff(x,lag = 1)}, align = "right"), by = list(variable)]
> dt
   variable value dif
1:      xyz     3   4
2:      xyz     7  -2
3:      xyz     5   4
4:      abc     9   1
5:      abc    10  -8
6:      abc     2   1
 
     
    