Home > Software engineering >  How I can get these differences in R
How I can get these differences in R

Time:04-25

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

CodePudding user response:

You can use mutate to make a new column that is equal to value minus the mean of value within each group:

library("dplyr")

dat %>%
    group_by(group) %>%
    mutate(out = value - mean(value))
# A tibble: 9 × 4
# Groups:   group [3]
#      id group value    out
#   <int> <int> <int>  <dbl>
# 1     1     1    10 -1.67 
# 2     2     1    11 -0.667
# 3     3     1    14  2.33 
# 4     4     2    17  1.33 
# 5     5     2    16  0.333
# 6     6     2    14 -1.67 
# 7     7     3    11 -1.67 
# 8     8     3    15  2.33 
# 9     9     3    12 -0.667

Although the result doesn't match what you posted.

  •  Tags:  
  • r
  • Related