Replace the first occurrence of certain text in R

Replace the first occurrence of certain text in R, To change the first instance of certain text within a string in R, use the sub() function.

Replace the first occurrence of certain text in R

The basic syntax used by this function is as follows:

Statistical Analysis» Statistics Methods » Quick Guide »

sub(pattern, replacement, x)

Example 1: Modify One Particular Text in a String

The R code below demonstrates how to change the word “cool” to the word “nice” in a string:

my_string <- 'This is a cool string' 
#replace 'cool' with 'nice' 
my_string <- sub('cool', 'super', my_string) 
my_string
"This is a super string"

Example 2: Replace a String with One of Several Specific Texts

The code below demonstrates how to change any occurrences of the words “zebra,” “walrus,” and “peacock” into the word “dog”:

my_string <- 'My favorite animal is a dog'

Replace either cow, dog, or peacock with cat

my_string <- sub('cow|dog|peacock', 'cat', my_string)

View updated string

my_string
"My favorite animal is a cat"

See how the string now reads “cat” instead of “dog”? Note: In R, the | operator denotes the “OR” operation.

Example 3: Replace String with Numeric Values

The code below demonstrates how to replace all numeric values with the word “a lot” in a string.

How Cloud Computing Improves Workflows in Data Science » Data Science Tutorials

my_string <- 'There are 4 dogs out here'

Replace numeric values with ‘a lot’

my_string <- sub('[[:digit:]]+', 'a lot of', my_string)

View updated string

my_string
[1] "There are a lot of dogs out here"

You will see that in the string, “a lot” has been used in place of the number 4.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

five − four =

finnstats