Use dummy variables to create a rank variable. R

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)

Topic dummy-variables ranking hierarchical-data-format r

Category Data Science


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")

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.