remove all punctuation from character in r

To remove all punctuation from a character string in R, you can use regular expressions and the gsub() function. The following code shows an example:

main.r
library(stringr)

sentence <- "This is a sentence! It has punctuation, and we want to remove it."

clean_sentence <- gsub("[[:punct:]]", "", sentence)

clean_sentence
# "This is a sentence It has punctuation and we want to remove it"
234 chars
9 lines

In this code, we first load the stringr package for string manipulation functions. We then define a character string sentence that includes punctuation. We use the gsub() function to replace all punctuation characters (identified by the regular expression [[:punct:]]) with an empty string. The resulting string with no punctuation is assigned to clean_sentence.

gistlibby LogSnag