MN Beitelmal
MN Beitelmal

Reputation: 165

Replacing multiple substrings of the same string simultaneously in R

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?

Upvotes: 4

Views: 274

Answers (2)

sgibb
sgibb

Reputation: 25726

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"

Upvotes: 3

akrun
akrun

Reputation: 887028

We can use chartr

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

Upvotes: 6

Related Questions