Here is my toy data. I have val and quartile variables q0 to q4.
df <- tibble::tribble(
~val, ~q0, ~q1, ~q2, ~q3, ~q4, ~q, ~diff,
15L, 15L, 15L, 15L, 15, 15L, 4L, 0,
17L, 2L, 16L, 30L, 34, 54L, 2L, 13,
29L, 2L, 16L, 30L, 34, 54L, 2L, 1,
25L, 2L, 17L, 20L, 26, 43L, 3L, 1 )
I need to calculate the last two variables such that:
- When val is between q1 and q2, I pick 2 (of q2) for variable q (2nd row)
- If there is a tie, I pick the max of qs (eg. q = 4 in 1st row)
- diff is the difference between q and val. So, for row 1, it's q4-val = 0 and for row 2, it's q2 - val = 30 - 17 = 13.
How can I calculate q and diff in R, preferably using tidyverse? May be we can leverage answers here: Extract column name and specific value based on a condition.