vendredi 9 avril 2021

Make pattern with two (multiple) conditions

My example dataframe (mine has more variables and more levels):

df <- data.frame('Endpoint1' = c('Cancer - (Ipsilateral)', 'Cancer - (Contralateral)', 'Wound - (Ipsilateral)',"Infection - (Ipsilateral)"), 
                 'Endpoint2' = c('Cancer - (Contralateral)', 'Cancer - (Ipsilateral)','Wound - (Ipsilateral)',"Infection - (Ipsilateral)"),
                 'Endpoint3' = c('Wound - (Ipsilateral)','Cancer - (Contralateral)', 'Cancer - (Ipsilateral)',"Infection - (Ipsilateral)"))

I want to subset a string based on a pattern with two conditions: I want either Wound + Infection in it, but both must be (Ipsilateral) (so (Contralateral) should be omitted). This code only checks the first condition (either Wound or Infection).

listlist <- c('Wound','Infection')

test <- df %>% 
  rowwise() %>%
  mutate(
    newname = str_subset(
      c_across(starts_with('Endpoint')),
      pattern = paste(listlist, collapse = "|")
    )[1])

I've not been able to add the second condition (must have of (Ipsilateral)) within the pattern.

In the end I want something like this (see variable newname):

data.frame('Endpoint1' = c('Cancer - (Ipsilateral)', 'Cancer - (Contralateral)', 'Wound - (Ipsilateral)',"Infection - (Ipsilateral)"), 
                 'Endpoint2' = c('Cancer - (Contralateral)', 'Cancer - (Ipsilateral)','Wound - (Ipsilateral)',"Infection - (Ipsilateral)"),
                 'Endpoint3' = c('Wound - (Ipsilateral)','Cancer - (Contralateral)', 'Cancer - (Ipsilateral)',"Infection - (Ipsilateral)"),
                 'newname' = c('Wound - (Ipsilateral)','Cancer - (Contralateral)', 'Wound - (Ipsilateral)',"Infection - (Ipsilateral)"))

                  Endpoint1                 Endpoint2                 Endpoint3                   newname
1    Cancer - (Ipsilateral)  Cancer - (Contralateral)     Wound - (Ipsilateral)     Wound - (Ipsilateral)
2  Cancer - (Contralateral)    Cancer - (Ipsilateral)  Cancer - (Contralateral)  Cancer - (Contralateral)
3     Wound - (Ipsilateral)     Wound - (Ipsilateral)    Cancer - (Ipsilateral)     Wound - (Ipsilateral)
4 Infection - (Ipsilateral) Infection - (Ipsilateral) Infection - (Ipsilateral) Infection - (Ipsilateral)

Aucun commentaire:

Enregistrer un commentaire