Data cleaning -- Creating one variable when multiple answers are chosen — in R

I am struggling with some r code. In my dataset, I have a slew of variables on drug use -- drug_mar, drug_coc, drug_her, drug_met, etc. I am trying to create a new variable for polysubstance use -- drug_poly. The problem is that I cannot seem to get a valid code that basically asks "if multiple drug variables are chosen, then drug_poly ==1"... I feel like I could do this in SPSS yet I cannot find the right r package or correct syntax. Any ideas?

This is my code that I was planning on putting after it... BUT I still haven't define how to create the drug_poly var.

    df <- df %>% 
      mutate(drug_type = ifelse(drug_mar == 1, 1,
           ifelse (drug_coc == 1, 2, 
                ifelse (drug_her == 1, 3,
                      ifelse (drug_met == 1, 4,
                             ifelse(drug_stim == 1, 5,
                                   ifelse(drug_ect == 1, 6,
                                         ifelse(drug_opi == 1, 7,
                                              ifelse(drug_other == 1, 8,
                                                   ifelse(drug_poly == 1, 9, NA))))))

I don't understand what you are trying to do but from your code, you might want to use dplyr::case_when() function instead of deeply nested ifelse() conditions.

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.