I tried
> str_replace("abcdef", c("b", "d"), c(b="B", d="D"))
[1] "aBcdef" "abcDef"
hoping for
[1] "aBcDef"
How can we replace each pattern with a specific replacement with one function call to stringr::str_replace?
The chartr() solution was new to me too, but I wanted to replace single characters with multiple. Eventually found a stringr (v1.4.0) solution that's quite simple. In fact it's in the help page, once it dawned that this calls for str_replace_all.
# one approach that both: answers the original question with stringr
str_replace_all("abcdef", c(b="B", d="D"))
[1] "aBcDef"
# and answers a more general question
str_replace_all("abcdef", c(b="BB", d="DDD"))
[1] "aBBcDDDef"
With str_replace an option is to wrap with reduce2
library(stringr)
library(purrr)
reduce2(c('b', 'd'), c('B', 'D'), .init = 'abcdef', str_replace)
#[1] "aBcDef"
Or with anonymous function call
reduce2(c('b', 'd'), c('B', 'D'), .init = 'abcdef',
~ str_replace(..1, ..2, ..3))
#[1] "aBcDef"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With