3
votes

Say I have a tibble of values:

raw = tibble(
    group = c("A", "B", "C", "A", "B", "C"),
    value = c(10, 20, 30, 40, 50, 60)
)

# A tibble: 6 x 2
  group value
  <chr> <dbl>
1     A    10
2     B    20
3     C    30
4     A    40
5     B    50
6     C    60

I want to subtract a certain amount from each value in my tibble depending on which group it belongs to. The amounts I need to subtract are in another tibble:

corrections = tibble(
    group = c("A", "B", "C"),
    corr = c(0, 1, 2)
)

# A tibble: 3 x 2
  group  corr
  <chr> <dbl>
1     A     0
2     B     1
3     C     2

What is the most elegant way to achieve this? The following works, but I feel like it is messy - surely there is another way?

mutate(raw, corrected = value - as_vector(corrections[corrections["group"] == group, "corr"]))

# A tibble: 6 x 3
  group value corrected
  <chr> <dbl>     <dbl>
1     A    10        10
2     B    20        19
3     C    30        28
4     A    40        40
5     B    50        49
6     C    60        58
1

1 Answers

3
votes

How about first joining raw and corrections and then calculating corrected?

library(dplyr)
left_join(raw, corrections, by = "group") %>% 
  mutate(corrected = value - corr) %>% 
  select(-corr) 

#> # A tibble: 6 x 3
#>   group value corrected
#>   <chr> <dbl>     <dbl>
#> 1     A    10        10
#> 2     B    20        19
#> 3     C    30        28
#> 4     A    40        40
#> 5     B    50        49
#> 6     C    60        58