Home > Software design >  How do I mutate numbers to a different scale in R?
How do I mutate numbers to a different scale in R?

Time:11-04

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
2,5,16
3,1,6
3,2,7
3,3,8
3,4,12
3,5,13")

I want to shift the y-scale from what it currently is to one that starts from 0. Right now, I have grouped this dataset by the "Group" variable. And I am trying to find the minimum "Y" value from each group and subtracting it from each value in the "Y" column of each group. However, this isn't working as intended. Any ideas on how I can do this? Thank you.

CodePudding user response:

This is a pretty simple use case for dplyr::group_by. Once you group the data.frame by your grouping variable, when you use functions like min or max in mutate, they will be called (and applied to) that group individually. So if we say Y=Y-min(Y) it will find the minimum value of Y in each group, and subtract it from the values of Y in that group

library(dplyr)
x %>%
    group_by(Group) %>%
    mutate(Y=Y-min(Y))

   Group     X     Y
   <int> <int> <int>
 1     1     1     0
 2     1     2     3
 3     1     3     6
 4     1     4     7
 5     2     1     0
 6     2     2     3
 7     2     3     7
 8     2     4     9
 9     2     5    15
10     3     1     0
11     3     2     1
12     3     3     2
13     3     4     6
14     3     5     7
  • Related