How to Use str_count in R (With Examples)

str_count() is a string manipulation function in R that counts the number of matching patterns in a string. It takes two parameters: the string to search and the pattern to search for. The function returns the number of times the pattern is found in the string. str_count() can be used to count the number of occurrences of a word, phrase, or character in a string. Examples of using str_count() include counting the number of vowels in a string, counting the number of words in a sentence, and counting the number of times a number appears in a list.


The str_count() function from the 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.

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

x