Replacing values without listing values

Hi,
I'm replacing values in the column "Specimen Source" and have the code below.
I still need to replace a huge list of the remaining values. Is there a way to do that without listing as in the code below? Maybe using something like an "else' step for example!
Processing: SpecSrc.JPG...

LAB<-LAB %>% #order matters, so go from the most specific to the most general
mutate(specimen_formatted= (case_when(
is.na(Specimen_Source) ~ "Missing",
grepl("Blood|Bld|Blood Specimen|Blood venous|Line Blood|Venous blood|", SpecimenSource, ignore.case = TRUE)~"Blood",
grepl("Blood|BLOOD CULTURE #1|BLOOD CULTURE (2ND SET)|BLOOD CULTURE (1ST SET)|BLOOD CULTURE|BLOOD CULTURE #2|CULTURE, BLOOD #1|CULTURE, BLOOD #2|FUNGAL BLOOD CULTURE|BACT CULT BLOOD|CULT BLOOD|CULTURE BLOOD|CULTURE, BLOOD", LocalTestDescription, ignore.case = TRUE)~"Blood")))

Thank you

Impossible to tell as you didn't share a reproducible example/data.

Two things though:

  • It's almost never a good idea to replace NA with a character string.
  • Regular expressions are meant to match patterns in character strings so passing the actual values cancels the purpose of using regex.

Do something like this instead:

blood_regex <- "(?i)blo{0,2}d"
data |> 
  mutate(specimen_formatted= case_when(
    grepl(blood_regex, SpecimenSource) | grepl(blood_regex, LocalTestDescription)~ "Blood",
    # more conditions
    .default = SpecimenSource
  ))

Sorry about that. I added sample data of what's needed.

This topic was automatically closed 42 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.