Globally substitute many patterns for many replacements

32 Views Asked by At

In R, we can use gsub to globally substitute one pattern by another pattern in a vector. However, if I want to substitute many patterns for many pattern, how can I do this. For ex:-

a <- c("AV. Reg", "AVENUE Reg", "Bld. Aze", "BOUlevard Aze", "Str. Fsd", "Strasse FSD", "R. Ger", "RUE Ger")

Now I want to substitute the following :-

pattern    replacement
AV.        Avenue
AVENUE     Avenue
Bld.       Boulevard
BOUlevard  Boulevard
Str.       Strasse
R.         Rue
RUE        Rue

Can I define pattern and replacement as two vectors and substitute pattern by replacement globally.

Thanks in advance.

1

There are 1 best solutions below

0
V. Lou On
a <- c("AV. Reg", "AVENUE Reg", "Bld. Aze", "BOUlevard Aze", "Str. Fsd", "Strasse FSD", "R. Ger", "RUE Ger")

pattern <- c("AV\\.","AVENUE","Bld\\.","BOUlevard", "Str\\.","R\\.","RUE")
replacement <- c("Avenue","Avenue","Boulevard","Boulevard","Strasse","Rue","Rue")

for(i in seq(pattern))
  a <- gsub(pattern[i], replacement[i], a)

Note the \ is to escape the "." special character ( you can check what happens if you remove them). Also, I changed your BLD. to Bld. cause I guess that what you meant