my mind is boggled by the circumstances that would require calculating this... but I had fun doing it anyway
library(tidyverse)
df <-
tibble::tribble(
~unique_id, ~group_id, ~time_one, ~time_two, ~rel_diff, ~desired_outcome,
1, 1, 10, 5, -5, -5,
2, 1, 10, 20, 10, -5,
3, 1, 10, 11, 1, 1,
4, 1, 10, 30, 20, 5,
5, 2, 25, 20, -5, -5,
6, 2, 25, 25, 0, 0,
7, 2, 25, 30, 5, 5
)
df2 <- mutate(rowwise(df),
uid = unique_id,
rel_diff_other_rows = list(crossing(
uid, time_two,
select(df, unique_id, time_one)
) %>%
filter(uid != unique_id) %>% mutate(
alt_rel_diffs = time_two - time_one
)),
min_alt_diff = min(rel_diff_other_rows$alt_rel_diffs),
final_calc_outcome = if_else(abs(min_alt_diff) - abs(rel_diff) > 0,
rel_diff,
min_alt_diff)
)