0

I am trying to create a new column (CoinfectionSpecified) based on if one of various viruses (I've specified the column indices) is detected (binary 0,1) in the sample AND the Influenza column is positive (binary 0,1). In CoinfectionSpecified, I want to list the virus detected with Influenza and separated by commas if there is more than one. I've been trying to wrap apply functions into if else statements but it keeps throwing out errors. e.g.

df <- df %>%
  mutate(CoinfectionSpecified = ifelse(Influenza == 1 & rowSums(df[, column_indices] == 1) > 0, 
                          paste(cols[df[, column_indices] == 1], collapse = ","), 
                          NA_character_)
         )
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Savannah
  • 1
  • 2
  • 3
    Please make this question *reproducible*. This includes sample *unambiguous* data (e.g., `data.frame(x=...,y=...)` or the output from `dput(head(x))` into a [code block]) and intended output given that input. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Aug 02 '23 at 14:38
  • I think this should be easier to do (and less messier) if you did it in steps instead of everything in a single ifelse(), i.e., first make a column or columns that returns TRUE or 1 of the row meets the condition or conditions for the concatenation, and then do the concatenation for rows where the conditions are meet. – Bastián Olea Herrera Aug 02 '23 at 15:18

0 Answers0