Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringr str_replace on multiple patterns and replacements?

Tags:

r

stringr

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?

like image 951
stevec Avatar asked Jan 31 '26 04:01

stevec


2 Answers

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"
like image 134
Scrope Avatar answered Feb 02 '26 20:02

Scrope


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"
like image 33
akrun Avatar answered Feb 02 '26 22:02

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!