Here is part of my data
dat<-read.table (text=" id group value
1 1 10
2 1 11
3 1 14
4 2 17
5 2 16
6 2 14
7 3 11
8 3 15
9 3 12
", header=TRUE)
I want to get the following table
id group valu dif
1 1 10 2
2 1 12 0
3 1 14 -2
4 2 18 -2
5 2 16 0
6 2 14 2
7 3 12 1
8 3 15 -2
9 3 12 1
The logic is that I calculate the mean for each group and then subtract the mean from the value based on each group. For example, the mean group 1 is 12. so 12-10=2, 12-12=0 and 12-14=-2. this repeat for other groups