str_replace & str_replace_all Functions in R (2 Examples)


In this post you’ll learn how to replace matched patterns in character strings with the str_replace and str_replace_all functions in the R programming language.

The article contains this content:

Let’s dig in!


Creation of Example Data

Let’s create a character string that we can use in the examples of this R tutorial.

x <- c("a very nice character string")    # Create character string

As next step, we need to install and load the stringr add-on package.

install.packages("stringr")               # Install stringr package
library("stringr")                        # Load stringr package


Example 1: Application of str_replace Function in R

After loading the stringr package, we can now apply the str_replace function as follows:

str_replace(x, "c", "xxx")                # Apply str_replace function
# "a very nixxxe character string"

The RStudio console output is showing the result. The first “c” in our character string was replaced by “xxx”.


Example 2: Application of str_replace_all Function in R

If we want to replace all occurrences of a certain pattern, we need to use the str_replace_all function:

str_replace_all(x, "c", "xxx")            # Apply str_replace_all function
# "a very nixxxe xxxharaxxxter string"

As you can see, this time we replaced every “c” with the replacement “xxx”.


Video, Further Resources & Summary

Do you want to know more about character strings in R? Then you could watch the following video instruction of my YouTube channel. In the video tutorial, I show the R syntax of the present tutorial in a live programming session:


The YouTube video will be added soon.


Additionally, you may have a look at the other articles of Statistics Globe. I have published numerous articles already:


In this R programming tutorial you learned how to change matched patterns in strings. Let me know in the comments section below, in case you have additional questions or comments.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

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.