str_replace_all with multiple vector patterns

I would like to replace one pattern given by a list by the other pattern given by another list.
I do it like this:

strings$old <- c("apple banana orange", "peach apple orange", "apple orange pear", "orange apple banana", "apple orange peach")
words to replace <- c("banana", "peach", "pear")
replacements <- c("b", "p", "pe")

what I do:
current <- paste(c(replace), collapse='|')
change_to <- paste(c(replacements ), collapse='|')
strings$new <-str_replace_all(strings$old, current, change_to)

However, I get an error. What I would like to see is:
c("apple b orange", "p apple orange", "apple orange pe", "orange apple b", "apple orange p")

Hi @gocoyd , maybe you need something like that:

library(stringr)

strings <- c("apple banana orange", "peach apple orange", "apple orange pear", "orange apple banana", "apple orange peach")
words_to_replace <- c("banana", "peach", "pear")
replacements <- c("b", "p", "pe")

current <- paste(words_to_replace, collapse='|')
change_to <- replacements

for(i in seq_along(words_to_replace)){
  strings <- str_replace_all(strings, words_to_replace[i], replacements[i])
}

strings
# [1] "apple b orange" 
# [2] "p apple orange" 
# [3] "apple orange pe"
# [4] "orange apple b" 
# [5] "apple orange p" 
1 Like

It works!! Thank you so much!! You saved a lot of my nerve cells))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.