Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

diff on data.table column

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
like image 744
user3385769 Avatar asked May 10 '16 14:05

user3385769


1 Answers

We could use shift():

dt[,diff := value - shift(value), by = variable]
> dt
   variable value diff
1:      xyz     3   NA
2:      xyz     7    4
3:      xyz     5   -2
4:      abc     9   NA
5:      abc    10    1
6:      abc     2   -8
like image 90
mtoto Avatar answered Sep 24 '22 21:09

mtoto