11.1 C
London
Sunday, July 7, 2024
HomeRDescriptive Statistics in RHow to Use sub() Function in R (With Examples)

How to Use sub() Function in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories