Mohaa Mohaa - 1 year ago 59
R Question

How to replace one substring with different substrings in R?

I have a vector of strings and I want to replace one common substring in all the strings with different substrings. I'm doing this in R. For example:

input=c("I like fruits","I like you","I like dudes")
# I need to do something like this

so that the output should look like:

"You like fruits"
"We like you"
"She like dudes"

However, gsub uses only the first string in newStrings. Any suggestions?

Answer Source

You can use stringr:

stringr::str_replace_all(input, "I" ,newStrings)

[1] "You like fruits" "We like you"    
[3] "She like dudes"

or as suggested by @ David Arenburg:

stringi::stri_replace_all_fixed(input, "I", newStrings)