poissonconsulting / tidyplus

An R package of additional tidyverse functions
https://poissonconsulting.github.io/tidyplus/
Other
9 stars 0 forks source link

Add function `str_replace_when` as vectorized form of `str_replace` #15

Closed nadinehussein closed 3 months ago

nadinehussein commented 1 year ago

in regular form if you're needing to use regex but have numerous strings you need to replace, it would look like:

mutate(chemical = str_replace(chemical, "\\-Total$", ""),
       chemical = str_replace(chemical, "\\-SO4", "(SO4)"))

and in the case_when format, in order to do multiple str_replace you have to do both a str_detect and str_replace , (which is even more bulky and repetitive) like so:

mutate(chemical = case_when(str_detect(chemical, "\\-Total$") ~ str_replace(chemical,  "\\-Total$", ""),
                            str_detect(chemical, "\\-SO4") ~ str_replace(chemical, "\\-SO4", "(SO4)"),
                            TRUE ~ chemical))

i'm not totally sure how it could be written out but in an ideal form, a vectorized str_replace would look something like:

mutate(chemical = str_replace_when(chemical, "\\-Total$", "",
                                   chemical, "\\-SO4", "(SO4)"))

or in a case_when format, it would still require a str_detect so something like:

mutate(chemical = str_replace_when(str_detect(chemical, "\\-Total$") ~ "",
                                   str_detect(chemical, "\\-SO4") ~ "(SO4)",
                                   TRUE ~ chemical))