R Language Pattern Matching and Replacement Making substitutions


Example

# example data
test_sentences <- c("The quick brown fox quickly", "jumps over the lazy dog")

Let's make the brown fox red:

sub("brown","red", test_sentences)
#[1] "The quick red fox quickly"       "jumps over the lazy dog"

Now, let's make the "fast" fox act "fastly". This won't do it:

sub("quick", "fast", test_sentences)
#[1] "The fast red fox quickly"       "jumps over the lazy dog"

sub only makes the first available replacement, we need gsub for global replacement:

gsub("quick", "fast", test_sentences)
#[1] "The fast red fox fastly"       "jumps over the lazy dog"

See Modifying strings by substitution for more examples.