In R programming, the `sub()` and `gsub()` functions are used for pattern matching and replacement in strings. Here's an explanation of these functions with a new example:
`sub()` function
The `sub()` function is used to substitute the first occurrence of a pattern in a string with a replacement value.
Example: Let's say we have a string "Hello World!" and we want to replace the word "World" with "Universe". We can use `sub()` for this.
string <- "Hello World!"
new_string <- sub("World", "Universe", string)
print(new_string)
Output:
Hello Universe!
In this example, the pattern "World" is matched in the string and replaced with "Universe".
`gsub()` function
The `gsub()` function is similar to `sub()`, but it replaces all occurrences of the pattern in a string.
Example: Let's consider the same string "Hello World!" and replace all occurrences of the letter "l" with "X".
string <- "Hello World!"
new_string <- gsub("l", "X", string)
print(new_string)
Output:
HeXXo WorXd!
In this example, all occurrences of the letter "l" are replaced with "X"