Match and replace multiple strings in a vector of text without looping in R

boomt picture boomt · Apr 2, 2015 · Viewed 11.5k times · Source

I am trying to apply gsub in R to replace a match in string a with the corresponding match in string b. For example:

a <- c("don't", "i'm", "he'd")
b <- c("do not", "i am", "he would")
c <- c("i'm going to the party", "he'd go too")
newc <- gsub(a, b, c)

with the desired result being

newc = c("i am going to the party", "he would go too")

This approach does not work because gsub only accepts a string of length 1 for a and b. Executing a loop to cycle through a and b will be very slow since the real a and b have a length of 90 and c has a length > 200,000. Is there a vectorized way in R to perform this operation?

Answer

G. Grothendieck picture G. Grothendieck · Apr 2, 2015

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"