Home > Mobile >  How can I subtract one group from other groups in R
How can I subtract one group from other groups in R

Time:11-17

x <- read.csv(text="Group,X,Y
1,1,2
1,2,5
1,3,8
1,4,9
2,1,1
2,2,4
2,3,8
2,4,10
3,1,6
3,2,7
3,3,8
3,4,12")

My goal here is to take group 1, Y and subtract it with group1, Y, group 2, Y and group 3, Y. So the resulting dataframe looks like this

x <- read.csv(text="Group,X,Y,Z
1,1,2,0
1,2,5,0
1,3,8,0
1,4,9,0
2,1,1,-1
2,2,4,-1
2,3,8,0
2,4,10,1
3,1,6,4
3,2,7,2
3,3,8,0
3,4,12,3")

How can I achieve this? I did something along the lines of this:

        group_by(Group) %>%
        mutate(Z = dataset2[Group != 1]-dataset2[Group == 1])```

CodePudding user response:

You don't need a group_by, you can substract column Y with Y[Group == 1] like this:

library(dplyr)
x %>%
  mutate(Z = Y - Y[Group == 1])
#>    Group X  Y  Z
#> 1      1 1  2  0
#> 2      1 2  5  0
#> 3      1 3  8  0
#> 4      1 4  9  0
#> 5      2 1  1 -1
#> 6      2 2  4 -1
#> 7      2 3  8  0
#> 8      2 4 10  1
#> 9      3 1  6  4
#> 10     3 2  7  2
#> 11     3 3  8  0
#> 12     3 4 12  3

Created on 2022-11-16 with reprex v2.0.2

  • Related