I'm not sure if I can succinctly describe what I want, so apologies in advance! I've included a desired outcome column below to try and illustrate what I want.
I want to find the relative difference between columns time_two
and time_one
but if the difference between time_two
and time_one
is less with a different time_one
row, then use that to find the difference. So take unique_id
2, we can see for that row that the relative difference with it's row is 20 - 10 = 10, but the difference between 20 and 25 is -5, so I want to use that value instead. The same goes for unique_id
4 too.
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
)