0
0
R Programmingprogramming~5 mins

sub and gsub in R Programming

Choose your learning style9 modes available
Introduction

Use sub and gsub to replace parts of text in strings. They help fix or change words easily.

Fix a typo in a sentence by changing the first wrong word.
Replace all spaces in a text with underscores for file names.
Change all occurrences of a word in a paragraph to another word.
Remove unwanted characters from a string, like punctuation.
Update a date format by replacing slashes with dashes.
Syntax
R Programming
sub(pattern, replacement, x)
gsub(pattern, replacement, x)

pattern is the text or pattern to find.

replacement is the new text to put instead.

Examples
Replaces only the first 'cat' with 'dog'. Result: "dog and cat"
R Programming
sub("cat", "dog", "cat and cat")
Replaces all 'cat' with 'dog'. Result: "dog and dog"
R Programming
gsub("cat", "dog", "cat and cat")
Replaces first 'a' with 'A'. Result: "bAnana"
R Programming
sub("a", "A", "banana")
Replaces all 'a' with 'A'. Result: "bAnAnA"
R Programming
gsub("a", "A", "banana")
Sample Program

This program shows how sub changes only the first 'cats' to 'dogs', while gsub changes all 'cats' to 'dogs'.

R Programming
text <- "I love cats and cats love me."
first_replace <- sub("cats", "dogs", text)
all_replace <- gsub("cats", "dogs", text)
print(first_replace)
print(all_replace)
OutputSuccess
Important Notes

sub changes only the first match it finds.

gsub changes every match in the string.

Both functions work with regular expressions for advanced matching.

Summary

sub replaces the first found text.

gsub replaces all found text.

Use them to clean or update text easily.