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

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -