How to Replace Substrings in R

04.23.2021

If you would like to replace portions of a string withe next text or remove some bad string values, R has a couple of options for you. In this article, we will learn how to replace substrings with R.

R provides two methods sub and gsub to allow you to replace substrings. The sub method has the following signatures sub(old, new, string) and will replace the first instance of the substring.

hello.string = "hello, world"

sub("world", "keith", hello.string)

# [1] "hello, keith"

The gsub method has the same signature gsub(old, new, string). The only difference here is that gsub will replace all instances of a sub string.

hello.string = "hello, world. Goodbye, world."

gsub("world", "keith", hello.string)

# [1] "hello, keith. Goodbye, keith."

Also note, that if you would like to remove a sub string, you can use these methods and replace with an empty string. This is a common use case.

replace.string = "A string % with some random % bad strings."

gsub("%", "", replace.string)

# [1] "A string  with some random  bad strings."