R String Replacement
Replacing text builds a new string with part of the old text swapped. sub and gsub differ in how many matches they swap.
The first match only
sub looks for a in banana. Only the first a changes to A.
print(sub("a", "A", "banana"))Every match
gsub looks for a in banana. All three matches change to A.
print(gsub("a", "A", "banana"))Each string in a vector
sub runs on each word in the vector. The first a in each word changes and the rest stay.
words <- c("banana", "avocado")
print(sub("a", "A", words))The dot matches any character
The pattern here is a single dot. The dot matches the first character, whatever it is.
print(sub(".", "-", "a.b"))A dot as plain text
The fixed argument turns the dot into a plain full stop. Only the full stop in the text changes.
print(sub(".", "-", "a.b", fixed = TRUE))Example
print(sub("cat", "dog", "cat and cat"))
print(gsub("cat", "dog", "cat and cat"))Key points
- sub swaps the first match in each string.
- gsub swaps every match in each string.
- Both calls take a pattern, a replacement, and the text to change.
- The original string stays unchanged.
- A dot in a pattern matches any single character.
- The fixed = TRUE argument treats the pattern as plain text.
In this example sub swaps only the first cat in the sentence. gsub swaps both cats and the whole sentence changes.
Note
sub and gsub work on each string in a vector in turn.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does print(gsub("a", "A", "banana")) show?