Delete all special characters from a string in R?

How to remove all special characters in a given string in R and replace each special character with a space?

Special characters to delete: ~!@#$%^&*(){}_+:"<>?,./;'[]-=

regex [:punct:] is about to do half the job.

Question_2: But how to remove, for example, these characters from foreign languages: â í ü Â á ą ę ś ć ?

Answer_2: Replace [^[:alnum:]] with [^a-zA-Z0-9] in regex or regexpr :
regex[^a-zA-Z0-9]

+49
string regex r character
Apr 24 '12 at 8:24
source share
3 answers

You need to use regular expressions to identify unwanted characters. For the most easily readable code, you want str_replace_all from the str_replace_all package, although gsub from the R base also works.

The exact regex depends on what you are trying to do. You could just delete the specific characters you asked in the question, but it’s much easier to remove all the punctuation marks.

 x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever str_replace_all(x, "[[:punct:]]", " ") 

(The basic equivalent of R is gsub("[[:punct:]]", " ", x) .)

An alternative is to replace all non-alphanumeric characters.

 str_replace_all(x, "[^[:alnum:]]", " ") 

Please note that determining what constitutes a letter or a number or a punctuation mark is slightly dependent on your language, so you may need to experiment a bit to get exactly what you want.

+105
Apr 24 '12 at 9:01
source share

Instead of using the regular expression to remove these crazy characters, just convert them to ASCII, which will remove the accents, bu will save the letters.

 astr <- "Ábcdêãçoàúü" iconv(astr, to = "ASCII//TRANSLIT") 

that leads to

 [1] "Abcdeacoauu" 
+1
Aug 29 '17 at 14:26
source share

Convert special characters to apostrophes,

 Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE) 

Below is the code to remove the extra `` apostrophe ''

 Data <- gsub("''","" , Data ,ignore.case = TRUE) 

Use the gsub(..) function to replace the special character with an apostrophe

0
Dec 12 '17 at 7:19
source share



All Articles