How to Remove Characters from String in R (3 Examples)


You can use the following methods to remove certain characters from a string in R:

Method 1: Remove One Specific Character from String

gsub('character', '', my_string)

Method 2: Remove Multiple Characters from String

gsub('[character1character2]', '', my_string)

Method 3: Remove All Special Characters from String

gsub('[^[:alnum:] ]', '', my_string)

The following examples show how to use each method in practice.

Method 1: Remove One Specific Character from String

The following code shows how to remove all instances of ‘WW‘ in a certain string:

#define string
my_string <- 'HeyWW My namWWe is Doug'

#replace 'WW' in string
my_string <- gsub('WW', '', my_string)

#view updated string
my_string

[1] "Hey My name is Doug"

Notice that all instances of ‘WW‘ have been removed from the string.

Method 2: Remove Multiple Characters from String

The following code shows how to remove all instances of ‘STRING1‘ and ‘STRING2‘ in a certain string:

#define some string
my_string <- 'HeySTRING1 My nameSTRING2 is DougSTRING2'

#replace WW in string
my_string <- gsub('[STRING1STRING2]', '', my_string)

#view updated string
my_string

[1] "Hey My name is Doug"

Notice that all instances of ‘STRING1‘ and ‘STRING2‘ have been removed from the string.

Method 3: Remove All Special Characters from String

The following code shows how to remove all special characters from a string.

Note: Special characters are any characters that are not numbers or letters.

#define string
my_string <- 'H*ey My nam%e is D!oug'

#replace all special characters in string
my_string <- gsub('[^[:alnum:] ]', '', my_string)

#view updated string
my_string

[1] "Hey My name is Doug"

Notice that all special characters have been removed from the string.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Find Location of Character in a String in R
How to Concatenate Strings in R
How to Convert a Vector to String in R
How to Convert Character to Factor in R

Leave a Reply

Your email address will not be published. Required fields are marked *