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" |
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" |
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" |
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.