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
?
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"
This matches each character and if it equals b
it replaces it with B
, if it equals d
it replaces it with D
and otherwise it leaves it as is.
library(gsubfn)
gsubfn(".", list(b="B", d="D"), "abcdef")
## [1] "aBcDef"
These also work:
gsubfn("[bd]", list(b="B", d="D"), "abcdef")
## [1] "aBcDef"
gsubfn("[bd]", toupper, "abcdef")
## [1] "aBcDef"
# only needs base R
chartr("bd", "BD", "abcdef")
## [1] "aBcDef"
I would put it in a pipe
str_replace('abcdef', 'b', 'B') %>% str_replace(., 'd', 'D')