R Language Pattern Matching and Replacement Making substitutions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any R Language Question?