The difference in the data.table column

Really upset by this. I just want to distinguish between rows in a data table. where dif (n) = value (n) is the value of (n-1). therefore, compared with what I have, the results should be shifted by 1 position, and the first position for each "variable" should be equal to NA. those. diff should be (NA, 4, -2, NA, 1, -8). The first value for each variable must be NA, because there is no position n-1. Any idea how I can change the function to accomplish this? I would like to know how I can do this with rollapplyr for my own understanding.

Thank.

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
+4
source share
2 answers

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
+11

:

dt[,dif := rollapplyr(value, 2, function(x){diff(x,lag = 1)},na.pad=TRUE), by = list(variable)]

> dt
   variable value dif
1:      xyz     3  NA
2:      xyz     7   4
3:      xyz     5  -2
4:      abc     9  NA
5:      abc    10   1
6:      abc     2  -8
+2

All Articles