GabyLP
GabyLP

Reputation: 3781

Replacing a list with a vector in R

I need to do many replacements. I'm using gsub. I was wondering if it's possible to do something like when I want to replace all á by a and all é by e:

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

Using this, I get an error.

If this is not possible, is there another function to do so?

Upvotes: 4

Views: 225

Answers (2)

flodel
flodel

Reputation: 89087

Yes, there is chartr:

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

Edit Since you now asked for a more general function that can handle whole words, here is what I would 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 is a bit 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 is probably great for many things but it might be overkill for your specific application.

Upvotes: 6

akrun
akrun

Reputation: 887391

You could do with mgsub from qdap

 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"

Upvotes: 2

Related Questions