0

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))))))))))
Shawna
  • 3
  • 1
  • 2
    Check dplyr function case_when. – José Jan 15 '21 at 22:25
  • Please illustrate your question with data (current and desired result). With clear structure, this will help understand your logic. [How to make a great R reproducible example](https://stackoverflow.com/q/5963269)? – Parfait Jan 15 '21 at 22:40

1 Answers1

0

Assuming all your drug variables are binary (0/1), simply use a single ifelse that adds all the drugs with arithmetic and checks if more than 1 is calculated:

if multiple drug variables are chosen, then drug_poly ==1

drugs <- c("drug_mar", "drug_coc", "drug_her", "drug_met",
           "drug_stim", "drug_ect", "drug_opi", "drug_other")

# CONVERT ALL NAs IN DRUG COLUMNS TO ZERO
df[drugs][is.na(df[drugs])] <- 0

# ASSIGN IF MORE THAN ONE DRUG IS CHOSEN
df$drug_poly <- with(df, ifelse((drug_mar + drug_coc + drug_her + drug_met + 
                                 drug_stim + drug_ect + drug_opi + drug_other) > 1, 1, 0
                                )
                     )

Even shorter with rowSums or Reduce

df$drug_poly <- ifelse(rowSums(df[drugs]) > 1, 1, 0)

df$drug_poly <- ifelse(Reduce(`+`, df[drugs]) > 1, 1, 0)
Parfait
  • 104,375
  • 17
  • 94
  • 125