The sub() function in R can be used to replace the first occurrence of certain text within a string in R.
This function uses the following basic syntax:
sub(pattern, replacement, x)
where:
- pattern: The pattern to look for
- replacement: The replacement for the pattern
- x: The string to search
The following examples show how to use this function in practice.
Note: To replace all occurrences of certain text in a string, use the gsub() function instead.
Example 1: Replace One Specific Text in String
The following code shows how to replace the text “cool” with “nice” in a string in R:
#create string my_string This is a cool string' #replace 'cool' with 'nice' my_string cool', 'nice', my_string) #view updated string my_string [1] "This is a nice string"
Notice that “cool” has been replaced with “nice” in the string.
Example 2: Replace One of Several Specific Texts in String
The following code shows how to replace the texts “zebra”, “walrus”, and “peacock” with “dog” if any of them occur in a string:
#create string my_string My favorite animal is a walrus' #replace either zebra, walrus, or peacock with dog my_string zebra|walrus|peacock', 'dog', my_string) #view updated string my_string [1] "My favorite animal is a dog"
Notice that “walrus” has been replaced with “dog” in the string.
Note: The | operator stands for “OR” in R.
Example 3: Replace Numeric Values in String
The following code shows how to replace all numeric values in a string with the text “a lot”:
#create string my_string There are 400 dogs out here' #replace numeric values with 'a lot' my_string [[:digit:]]+', 'a lot of', my_string) #view updated string my_string [1] "There are a lot of dogs out here"
Notice that the numeric value of 400 has been replaced with “a lot” in the string.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use diff Function in R
How to Use seq Function in R
How to Use diff Function in R