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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With