Keith Sanders
Keith Sanders

Reputation: 65

Using dplyr how can I divide grouped data by a specific value associated with that

I have a dataframe that looks like this:

Dose Treatment PE
0 Gy  RT      .75
2 Gy  RT      .60
4 Gy  RT      .30
0 Gy  P1      .52
2 Gy  P1      .21
4 Gy  P1      .15

I want to create a new column(SF) calculated by dividing the all values in the PE column by the dose "0 Gy" respective to their treatment

Ending up with something like:

Dose Treatment PE  SF
0 Gy  RT      .75  1
2 Gy  RT      .60 .8
4 Gy  RT      .30 .4 
0 Gy  P1      .52  1
2 Gy  P1      .21 .40
4 Gy  P1      .15 .29

How can I accomplish this? Is it possible to get this using dpylr?

Upvotes: 1

Views: 32

Answers (1)

akrun
akrun

Reputation: 886948

After grouping by 'Treatment', subset the 'PE' value where 'Dose' is '0 Gy' and use that to divide the whole 'PE' column

library(tidyverse)
df %>%
    group_by(Treatment) %>%
    mutate(SF = PE/PE[Dose == '0 Gy'])

Upvotes: 1

Related Questions