Replacing multiple substrings of the same string at the same time in R

I want to replace the Latin characters in a string vector with ordinary characters (e.g., from é to e, from a to, etc.). I also want to do this for a large vector, so I will replace these characters in a loop. I tried to do this in one 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 result is clearly not a suitable result:

> str_replace(phrase, "[ÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑÇ]", "[AAAEEEIIIOOOUUUNC]")
[1] "[AAAEEEIIIOOOUUUNC]ÉÍÓÚ"

Can someone help me replace all the special characters found with regular ones without opening the if statement for each special character separately?

+4
source share
2 answers

chartr :

phrase <- c("ÁÉÍÓÚ", "ÚÓÍÉÁ")
spec.elements <- c("ÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑÇ")
spec.elements.rep <- c("AAAEEEIIIOOOUUUNC")
chartr(old=spec.elements, new=spec.elements.rep, x=phrase)
# [1] "AEIOU" "UOIEA"
+3

chartr

if(grepl(spec.elements, phrase)){
 chartr('ÁÚ', 'AU', phrase)}
 #[1] "AÉÍÓU"
+6

Source: https://habr.com/ru/post/1609941/


All Articles