timothy
timothy

Reputation: 17

divide each value by unique value from a level of factor

I would like to divide each value by "q" grouped on id. So each id´s unique "q" should divide each id´s unique "comb_abc" and "q". The end result for id A1 would be comb_abc = 3.333 and q = 1. I have more levels for each id than these two, but this example is for the sake of simplicity. What kind of code would do the trick? THANKS! I have a data that looks like this:

#  id    event     value
#  <chr> <chr>     <dbl>
#1 A1    comb_abc     10
#2 A1    q            3
#3 B2    comb_abc     18
#4 B2    q            6
#5 C3    comb_abc     15
#6 C3    q            7

Upvotes: 0

Views: 126

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

We can use match to get the index of value corresponding to 'q' event.

library(dplyr)

df %>%
  group_by(id) %>%
  mutate(val = value/value[match('q', event)])

#  id    event    value   val
#  <chr> <chr>    <int> <dbl>
#1 A1    comb_abc    10  3.33
#2 A1    q            3  1   
#3 B2    comb_abc    18  3   
#4 B2    q            6  1   
#5 C3    comb_abc    15  2.14
#6 C3    q            7  1   

If the 'q' event is last in each group we can also use :

df %>%
  group_by(id) %>%
  mutate(val = value/last(value))

Upvotes: 1

Related Questions