I am looking to replace Latin characters in a vector of strings to normal characters (e.g. é to e, á to a, etc). I am also looking to do this for a large vector, so I will be replacing these characters in a loop. I have attempted to do this with a single word below:
phrase <- "ÁÉÍÓÚ"
spec.elements <- c("[ÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑÇ]")
if (str_detect(phrase,spec.elements) == TRUE){
str_replace(phrase, "Á", "A") & str_replace(phrase, "Ú", "U")
}
and I get the following error:
Error in str_replace(phrase, "Á", "A") & str_replace(phrase, "Ú", "U") :
operations are possible only for numeric, logical or complex types
I also tried the following and the output is clearly not the appropriate result:
> str_replace(phrase, "[ÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑÇ]", "[AAAEEEIIIOOOUUUNC]")
[1] "[AAAEEEIIIOOOUUUNC]ÉÍÓÚ"
Could anyone help me replace all the special characters detected to the regular ones, without opening an if statement for each special character individually?
We can use chartr
if(grepl(spec.elements, phrase)){
chartr('ÁÚ', 'AU', phrase)}
#[1] "AÉÍÓU"
Maybe chartr
fulfill your needs:
phrase <- c("ÁÉÍÓÚ", "ÚÓÍÉÁ")
spec.elements <- c("ÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑÇ")
spec.elements.rep <- c("AAAEEEIIIOOOUUUNC")
chartr(old=spec.elements, new=spec.elements.rep, x=phrase)
# [1] "AEIOU" "UOIEA"
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