R Data table - how to use previous row value within group [duplicate]
问题 This question already has answers here : How to create a lag variable within each group? (5 answers) Closed 5 years ago . I wish to calculate the difference between the current row and previous row, by groups. x = data.table(a=c(15, 25, 10, 12), b = c(1,1,2,2)) > x a b 1: 15 1 2: 25 1 3: 10 2 4: 12 2 > x[, c:= a - c(NA, a[.I-1]), by=b] Warning messages: 1: In a - c(NA, a[.I - 1]) : longer object length is not a multiple of shorter object length 2: In `[.data.table`(x, , `:=`(c, a - c(NA, a[.I