How to Use str_count in R (With Examples)


The str_count() function from the stringr package in R can be used to count the number of matches in a string.

This function uses the following syntax:

str_count(string, pattern = “”)

where:

  • string: Character vector
  • pattern: Pattern to look for

The following examples show how to use this function in practice

Example 1: Use str_count with One Pattern

The following code shows how to use the str_count() function to count the number of times the letter ‘a’ occurs in each element in a character vector:

library(stringr)

#create character vector
x <- c('Mavs', 'Cavs', 'Nets', 'Trailblazers', 'Heat')

#count number of times 'a' occurs in each element in vector
str_count(x, 'a')

[1] 1 1 0 2 1

Here’s how to interpret the output:

  • The pattern ‘a’ occurs 1 time in ‘Mavs’
  • The pattern ‘a’ occurs 1 time in ‘Cavs’
  • The pattern ‘a’ occurs 0 times in ‘Nets’

And so on.

Note that str_count() is also case-sensitive, so a capital ‘A’ would return 0 for each element in the character vector.

Example 2: Use str_count with Multiple Patterns

The following code shows how to use the str_count() function to count the number of times the letter ‘a’ or the letter ‘s’ occurs in each element in a character vector:

library(stringr)

#create character vector
x <- c('Mavs', 'Cavs', 'Nets', 'Trailblazers', 'Heat')

#count number of times 'a' or 's' occurs in each element in vector
str_count(x, 'a|s')

[1] 2 2 1 3 1

Here’s how to interpret the output:

  • The pattern ‘a’ or ‘s’ occurs 2 times in ‘Mavs’
  • The pattern ‘a’ or ‘s’ occurs 2 times in ‘Cavs’
  • The pattern ‘a’ or ‘s’ occurs 1 time in ‘Nets’

Note: The | symbol represents an “OR” operator in R.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use str_replace in R
How to Use str_split in R
How to Use str_detect in R

Leave a Reply

Your email address will not be published.