R – How to Replace Set of Words with Another Set of Words in R

rreplacestringsubset

It is a simple question. I have a list of country names. However, I wanted to change few names with correct names. So, I have two more vectors; one with names to be changed, and second with correct names. See the example:

#country names (names are repetitive in the list)
cn <- c("I", "A", "B", "C", "A", "C", "D", "P")

change <- c("A", "B")
tochange <- c("X", "Y")

Expected Output

cn <- c("I", "X", "Y", "C", "X", "C", "D", "P")

Thanks

Best Answer

Uisng stringi::stri_replace_all_fixed.

> stringi::stri_replace_all_fixed(cn, change, tochange, vectorize_all=FALSE)
[1] "I" "X" "Y" "C" "X" "C" "D" "P"