To remove special characters from a string in R, you can use the gsub() function with a regular expression pattern.
In this example,
str1
with a value of "Hello! World!"
.gsub()
function with a regular expression pattern "[^a-zA-Z0-9 ]"
to replace all non-alphanumeric characters and spaces with an empty string.str1
.str1 <- "Hello! World!"
str1 <- gsub('[^a-zA-Z0-9 ]', '', str1)
cat('Modified string:', str1)
Modified string: Hello World
In this example,
str2
with a value of "apple@banana"
.gsub()
function with a regular expression pattern "[^a-zA-Z0-9 ]"
to replace all non-alphanumeric characters and spaces with an empty string.str2
.str2 <- "apple@banana"
str2 <- gsub('[^a-zA-Z0-9 ]', '', str2)
cat('Modified string:', str2)
Modified string: applebanana
In this tutorial, we learned How to Remove Special Characters from a String in R language with well detailed examples.