Replacing a list with a vector in R

I need to make many replacements. I am using gsub. I was wondering if it is possible to do something like when I want to replace all a with a and all with e:

gsub(c("á","é"),c("a","e"),"ána belén")

Using this, I get an error message.

If this is not possible, is there another function?

+4
source share
2 answers

You can do with mgsubfromqdap

 library(qdap)
 mgsub(c("á","é"),c("a","e"),"ána belén")
 #[1] "ana belen"

Also replace words

 mgsub(c("cat", "dog", "mouse"),c("lion", "bulldog", "elephant"),
                         c("cat", "dog", "dog", "mouse", "ant", "mouse"))
 #[1] "lion"     "bulldog"  "bulldog"  "elephant" "ant"      "elephant"
+2
source

Yes there are chartr:

chartr("áé" ,"ae","ána belén")
# [1] "ana belen"

Change . Since now you have asked for a more general function that can handle whole words, here is what I will do:

rgsub <- function(pattern, replacement, x) {
   ARGS <- Map(c, pattern = pattern, replacement = replacement)
   FUN  <- function(x, y) gsub(y[['pattern']], y[['replacement']], x)
   Reduce(FUN, ARGS, x)
} 

To show that it gives the same results as qdap, but a little faster:

i <- c("cat", "dog", "mouse")
j <- c("lion", "bulldog", "elephant")
k <- c("cat", "dog", "dog", "mouse", "ant", "mouse")

identical(mgsub(i, j, k), rgsub(i, j, k))
# [1] TRUE

library(microbenchmark)

microbenchmark(mgsub(i, j, k), rgsub(i, j, k))
# Unit: microseconds
#            expr    min       lq   median       uq      max neval
#  mgsub(i, j, k) 586.60 608.6920 629.7840 659.2415 1278.973   100
#  rgsub(i, j, k)  81.91  88.9305  97.0165 107.2390  229.835   100

qdap, , , .

+6

All Articles