I have data
dat <- data.table(id=1:8, group=c(1,1,2,2,2,3,3,3), val=c(4,10,5,10,10,6,10,10))
> dat
id group val
1: 1 1 4
2: 2 1 10
3: 3 2 5
4: 4 2 10
5: 5 2 10
6: 6 3 6
7: 7 3 10
8: 8 3 10
and I would like to subtract from each the first value of its respective group
.
> res
id group val dif
1: 1 1 4 0
2: 2 1 10 6
3: 3 2 5 0
4: 4 2 10 5
5: 5 2 10 5
6: 6 3 6 0
7: 7 3 10 4
8: 8 3 10 4
I am always astonished by the efficiency of data.table
so I'm wondering whether it can offer a solution. Of course any other efficient method is just as welcome.