of course I could replace specific arguments like this:
mydata=c("á","é","ó")
mydata=gsub("á","a",mydata)
mydata=gsub("é","e",mydata)
mydata=gsub("ó","o",mydata)
mydata
but surely there is a easier way to do this all in onle line, right? I dont find the gsub help to be very comprehensive on this.
Use the character translation function
chartr("áéó", "aeo", mydata)
An interesting question! I think the simplest option is to devise a special function, something like a "multi" gsub():
mgsub <- function(pattern, replacement, x, ...) {
if (length(pattern)!=length(replacement)) {
stop("pattern and replacement do not have the same length.")
}
result <- x
for (i in 1:length(pattern)) {
result <- gsub(pattern[i], replacement[i], result, ...)
}
result
}
Which gives me:
> mydata <- c("á","é","ó")
> mgsub(c("á","é","ó"), c("a","e","o"), mydata)
[1] "a" "e" "o"
Maybe this can be usefull:
iconv('áéóÁÉÓçã', to="ASCII//TRANSLIT")
[1] "aeoAEOca"
You can use stringi
package to replace these characters.
> stri_trans_general(c("á","é","ó"), "latin-ascii")
[1] "a" "e" "o"
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