str_remove & str_remove_all Functions in R (Example)

 

In this R programming tutorial you’ll learn how to remove matched patterns in a character string with str_remove and str_remove_all.

Table of contents:

It’s time to dive into the R code:

 

Constructing Exemplifying Data

Let’s create some data that we can use in the following examples:

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

In order to use the str_remove and str_remove_all functions, we also 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_remove Function in R

In this example, we’ll use the str_remove function to remove certain values from our character string x. Have a look at the following R code:

str_remove(x, "c")                        # Apply str_remove function
# "a very nie character string"

As you can see based on the RStudio console output, the previous R code removed the first “c” of our character string, leading to the word “nie” instead of “nice”.

However, the remaining “c” remained. If we want to remove all “c” from our string, we need to use the str_remove_all command. So let’s move on to the next example…

 

Example 2: Application of str_remove_all Function in R

We can eliminate all “c” from our character string with the str_remove_all function as shown below:

str_remove_all(x, "c")                    # Apply str_remove_all function
# "a very nie harater string"

No “c” left – looks good!

 

Video, Further Resources & Summary

I have recently released a video on my YouTube channel, which illustrates the topics of the present article. You can find the video below.

 

The YouTube video will be added soon.

 

Furthermore, I can recommend to have a look at the other R articles that I have published on this website. A selection of tutorials is listed here.

 

In summary: In this article, I explained how to eliminate matched patterns in a character string in R programming. If you have additional questions, please let me know in the comments below. Furthermore, please subscribe to my email newsletter in order to get updates on new tutorials.

 

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.

Top