sub() and gsub() function in R

sub() and gsub() function in R are replacement functions, which replaces the occurrence of a substring with other substring.

  • sub() Function in R replaces the first instance of a substring
  • gsub() function in R replaces all the instances of a substring

Syntax for sub() and gsub() function in R:

  1. sub(old, new, string)

2. gsub(old, new, string)

Example of sub() function in R:

sub() function in R replaces only the first occurrence of a substring. The sub function finds the first instance of the old substring and replaces it with the new substring. let’s see with an example.

# sub function in R

mysentence <- "England is Beautiful. England is not the part of EU"
sub("England", "UK", mysentence)

only England in the first occurrence is replaced with UK. so the output will be

[1] “UK is Beautiful. England is not the part of EU”

 

Example of gsub() function in R:

   gsub() function in R is global replace function, which replaces all instances of the substring not just the first. Lets see the same example

# gsub function in R

mysentence <- "England is Beautiful. England is not the part of EU"
gsub("England", "UK", mysentence)

all the occurrences of England is replaced with UK. so the output will be

[1] “UK is Beautiful. UK is not the part of EU”

Example of gsub() function with regular expression in R:

 The old argument in the syntax can be a regular expression, which allows you to match patterns in which you want to replace a substring. Lets see an example

# gsub function in R with regular expression

mysentence <- "UK is Beautiful. UK is not the part of EU since 2016"
gsub("[0-9]*", "", mysentence)

In the above example we have removed all the numbers from the sentence with the help of regular expression.

So the output will be

[1] “UK is Beautiful. UK is not the part of EU since “

previous small sub() and gsub() function in R                                                                                                                next small sub() and gsub() function in R