Hi all,
I have three independent variables I need to collapse into a single variable--but this needs to be done conditionally. Example tibble here:
ex_data=tibble::tribble(
~subject_id, ~treat_1, ~treat_1a, ~treat_1b,
"1001", "Perphenazine", "Quetiapine", NA,
"1002", "Quetiapine", NA, NA,
"1004", "Olanzapine", NA, NA,
"1005", "Quetiapine", NA, NA,
"1006", "Perphenazine", NA, "Quetiapine",
"1007", "Olanzapine", NA, NA,
"1008", "Risperidone", NA, "Quetiapine",
"1009", "Risperidone", NA, NA,
"1011", "Quetiapine", "Olanzapine", NA,
"1012", "Quetiapine", NA, NA,
"1013", NA, "Olanzapine", NA)
The current trials have each person assigned at least one medication, with some people being re-assigned to a different medication at a later time, based on study design reasons. What I need to do is collapse these three columns into a new variable I want to call "final_medication" that has only the latest assigned medication. So for example, if treat_1
is not blank but treat_1a
and treat_1b
are NA, then final_medication
should be the string from treat_1
; but if treat_1a
is not NA, than final_medication
should equal the string in that column; etc.
Any ideas how to do this? I'm thinking it's probably a good spot to use dplyr::case_when()
, but I'm not sure how to write the code