Match and replace multiple strings in a vector of text without looping in R
1) gsubfn gsubfn
in the gsubfn package is like gsub
except the replacement string can be a character string, list, function or proto object. If its a list it will replace each matched string with the component of the list whose name equals the matched string.
library(gsubfn)
gsubfn("\\S+", setNames(as.list(b), a), c)
giving:
[1] "i am going to the party" "he would go too"
2) gsub For a solution with no packages try this loop:
cc <- c
for(i in seq_along(a)) cc <- gsub(a[i], b[i], cc, fixed = TRUE)
giving:
> cc
[1] "i am going to the party" "he would go too"
stringr::str_replace_all()
is an option:
library(stringr)
names(b) <- a
str_replace_all(c, b)
[1] "i am going to the party" "he would go too"
Here is the same code but with different labels to hopefully make it a little clearer:
to_replace <- a
replace_with <- b
target_text <- c
names(replace_with) <- to_replace
str_replace_all(target_text, replace_with)