Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (7.3k points)

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

The special characters to remove are : [email protected]#$%^&*(){}_+:"<>?,./;'[]-=

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

1 Answer

0 votes

To remove all special characters from a string, you can use the string_replace_all function from the stringr package as follows:

To remove all the punctuation characters:

x <- "[email protected]#$%^&*(){}_+:\"<>?,./;'[]-="

str_replace_all(x, "[[:punct:]]", " ")

[1] "a1~   $ ^       +  <>         ="

To remove all the non-alphanumeric characters:

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

[1] "a1 

You can also use the gsub function from the base package as follows:

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

[1] "a1   

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

29.3k questions

30.6k answers


104k users

Browse Categories