Replace string in R with patterns and replacements both vectors -


let's have 2 vectors so:

a <- c("this", "is", "test") b <- c("that", "was", "boy") 

i have string variable so:

string <- "this story test" 

i want replace values in string becomes following:

string <- "that story boy" 

i using loop want vectorized. how should this?

if you're open using non-base package, stringi work here:

stringi::stri_replace_all_fixed(string, a, b, vectorize_all = false) #[1] "that story boy" 

note works same way input strings of length > 1.

to on safe side, can adapt - similar ruser's answer - check word boundaries before replacing:

stri_replace_all_regex(string, paste0("\\b", a, "\\b"), b, vectorize_all = false) 

this ensure don't accidentally replace his hwas, example.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -