1
$\begingroup$

I have a series of multiple response (dummy) variables describing causes for a canceled visits. A visit can have multiple reasons for the cancelation. My goal is to create a single mutually exclusive variable using the dummy variables in a hierarchical way. For example, in my sample data below the rank of my variables is as follow: Medical, NoID and Refuse. Ex. if a visit was cancelled due to medical and lack of ID reasons, I would like to recode my final variable as "medical" since is more important base on my rank. Likewise VisitID 3 was cancelled due to no ID and refuse visit, in this case I would like to recode this cancellation as NoID since NoID is more important than Refuse.
Thank you for any help!

  VisitID  NoID Refuse Medical WhatINeed
1       1  TRUE  FALSE    TRUE   Medical
2       2 FALSE  FALSE   FALSE      <NA>
3       3  TRUE   TRUE   FALSE      NoID
structure(list(VisitID = c(1, 2, 3), NoID = c(TRUE, FALSE, TRUE
), Refuse = c(FALSE, FALSE, TRUE), Medical = c(TRUE, FALSE, FALSE
), WhatINeed = c("Medical", NA, "NoID")), row.names = c(NA, 3L
), class = "data.frame")
$\endgroup$

1 Answer 1

1
$\begingroup$

You can use case_when() and list the conditions in the order of your rank. Since your dummy variables are already os type logical, the following should work:

df %>% 
  mutate(
    WhatINeed_2 = case_when(
      Medical ~ "Medical",
      NoID ~ "NoID", 
      Refuse ~ "Refuse", 
      TRUE ~ NA_character_
    )
  )
  VisitID  NoID Refuse Medical WhatINeed WhatINeed_2
1       1  TRUE  FALSE    TRUE   Medical     Medical
2       2 FALSE  FALSE   FALSE      <NA>        <NA>
3       3  TRUE   TRUE   FALSE      NoID        NoID

data

df <- structure(list(VisitID = c(1, 2, 3), NoID = c(TRUE, FALSE, TRUE
), Refuse = c(FALSE, FALSE, TRUE), Medical = c(TRUE, FALSE, FALSE
), WhatINeed = c("Medical", NA, "NoID")), row.names = c(NA, 3L
), class = "data.frame")
$\endgroup$
1
  • $\begingroup$ Thank you Marcelo. It work perfectly. $\endgroup$
    – Mar355
    Jul 14, 2021 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.