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 |
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" |
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" |
gsub("x", "Y", my_string) # Application of gsub # "YYYabcYaaYa"