← Back to R Course | Chapter 6: Strings | Lesson 5 of 7

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:

  1. gsub and sub
Syntax
r
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

markup
text <- "cat bat cat sat"

cat(sub("cat", "dog", text), "\n")
cat(gsub("cat", "dog", text), "\n")
cat(gsub("[aeiou]", "*", text), "\n")
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
  1. Using sub and expecting every match to change, when it only replaces the first; use gsub.
  2. Using . or + in the pattern as plain characters, when they are regex symbols; use fixed = TRUE or escape with \\..
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.