sub & gsub Functions in R (Example)

This article explains how to replace a character pattern in a string with the sub() and gsub() functions in the R programming language.

Example Data

my_string <- "xxxabcxaaxa"    # Create example data

Applying sub Function

The sub function replaces only the first match of a pattern:

sub("x", "Y", my_string)      # Application of sub
# "Yxxabcxaaxa"

Applying gsub Function

The gsub function replaces all matches of a pattern:

gsub("x", "Y", my_string)     # Application of gsub
# "YYYabcYaaYa"

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top