R Exchange Certain Character Pattern in String (2 Examples)

In this article, I’ll illustrate how to replace characters in strings in the R programming language.

Creation of Example Data

my_character <- "YAYAYAYA XX YAYA XX YAYAYAYAYAAAA"

Example 1: Using sub() Function to Replace First Appearance of Character Pattern in String

sub("XX", "OOOOO", my_character)     # Using sub function in R
# "YAYAYAYA OOOOO YAYA XX YAYAYAYAYAAAA"

Example 2: Using sub() Function to Replace All Appearances of Character Pattern in String

gsub("XX", "OOOOO", my_character)    # Using gsub function in R
# "YAYAYAYA OOOOO YAYA OOOOO YAYAYAYAYAAAA"

Related Articles

Below, you can find some further resources that are related to the topic of this article.

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top