str_count Function in R (stringr Package)


In this tutorial you’ll learn how to use the str_count function to count the number of matches in a character string in R.

The content of the page is structured as follows:

Here’s the step-by-step process!


Creation of Example Data

Before we can start with the example, we need to create an exemplifying character string in R:

x <- "hello R user, this is my string"   # Create example character string

As you can see, our example string simply contains the sentence “hello R user, this is my string”. Now let’s apply the str_count command of the stringr package to this character string…


Example: Count Number of Matches in String

In order to use functions of the stringr package, we need to install and load the package first:

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

Now we can apply the str_count function as follows:

str_count(x, "is")                       # Apply str_count function
# 2

In the previous R syntax, we are checking how often the pattern “is” appears within our example character string x. As you can see based on the output of the RStudio console, the result is two times.


Video & Further Resources

In case you need more explanations on the examples of this tutorial, I can recommend to have a look at the following video of my YouTube channel. I’m explaining the R codes of this tutorial in the video.


The YouTube video will be added soon.


Furthermore, you might want to read the related articles of my website.


In summary: This tutorial showed how to get the amount of matches of a certain pattern within a character string in R. Let me know in the comments, if you have additional questions.


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.