In this article, we are going to remove all special characters from strings in R Programming language.
For this, we will use the str_replace_all() method to remove non-alphanumeric and punctuations which is available in stringr package.
Installation
To install this library type the below command in the terminal.
install.packages("stringr")
We will remove non-alphanumeric characters by using str_replace_all() method.
Syntax: str_replace_all(string, "[^[:alnum:]]", "")
where
- string is the input string
- [^[:alnum:]] is the parameter that removes the non-alphanumeric characters.
Example 1: R program to remove non-alphanumeric characters from the string
# load the stringr package
library("stringr")
# string
string = "a37935fguiegfkeu#$^VYVJ&(*&TFYJ"
# display original string
print(string)
# remove non alphanumeric characters
print(str_replace_all(string, "[^[:alnum:]]", ""))
Output:
[1] "a37935fguiegfkeu#$^VYVJ&(*&TFYJ" [1] "a37935fguiegfkeuVYVJTFYJ"
Example 2: Remove the punctuations from the string
Syntax: str_replace_all(string, "[[:punct:]]", "")
Where, [[:punct:]: This will remove the punctuations from the string
# load the stringr package
library("stringr")
# string
string = "a37935fguiegfkeu#$^VYVJ&(*&TFYJ"
# display original string
print(string)
# remove punctuations characters
print(str_replace_all(string, "[[:punct:]]", ""))
Output:
[1] "a37935fguiegfkeu#$^VYVJ&(*&TFYJ" [1] "a37935fguiegfkeu$^VYVJTFYJ"