gsub and sub
sub and gsub find a pattern in text and swap it for something else, like the Find and Replace in a document. sub changes just the first one, while gsub changes them all.
In this page:
Syntax
sub(pattern, replacement, x)
gsub(pattern, replacement, x)
gsub and sub
sub(pattern, replacement, x) replaces the first match of a pattern in a string, while gsub() replaces every match (the g stands for global).
Both support regular expressions by default, making them powerful for pattern-based text transformation. This mirrors the relationship between sed's single and global replace modes.
Note:
Use fixed = TRUE in sub()/gsub() when your pattern is a literal string, not a regex, to avoid special-character surprises.
Example: gsub and sub
text <- "cat bat cat sat"
cat(sub("cat", "dog", text), "\n")
cat(gsub("cat", "dog", text), "\n")
cat(gsub("[aeiou]", "*", text), "\n")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
suband expecting every match to change, when it only replaces the first; usegsub. - Using
.or+in the pattern as plain characters, when they are regex symbols; usefixed = TRUEor escape with\\.. - Swapping the argument order, when the pattern comes first, then the replacement and then the text.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: