Count Number of Occurrences of Certain Character in String in R (2 Examples)

 

In this tutorial you’ll learn how to get the number of times a specific character occurs in a string in the R programming language.

The page looks as follows:

It’s time to dive into the R syntax:

 

Introduction of Example Data

We’ll use the following character string as basement for the examples of this R programming tutorial:

x <- "ajdvmaamfsjdaaa"
x
# "ajdvmaamfsjdaaa"

Our example string contains a random sequence of characters.

 

Example 1: Count Character with Base R

Example 1 shows how to count the number of occurrences of a specific letter using the functions of the basic installation of the R programming language. More precisely, we are applying the lengths, regmatches, and gregexpr functions:

lengths(regmatches(x, gregexpr("a", x)))
# 6

The RStudio console returns the value 6, i.e. our string contains the character a 6 times.

 

Example 2: Count Character with stringr Package

As you have seen in Example 1, we can count the occurrence of a character with the basic functions of the R programming language. However, the stringr package provides a much simpler solution. First, we need to install and load the package:

install.packages("stringr")
library("stringr")

Now, we can apply the str_count function to get the same result as in Example 1:

str_count(x, "a")
# 6

 

Video, Further Resources & Summary

In case you need further info on the R programming codes of this tutorial, you may want to have a look at the following video of my YouTube channel. I’m explaining the R programming code of this article in the video.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

In addition, I can recommend to have a look at the other posts of this homepage. You can find a selection of tutorials below:

 

In this tutorial, I showed how to how to calculate the number of occurrences of a certain character in a string in R programming. Let me know in the comments section below, in case you have further 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.

Top