20.7 C
London
Saturday, July 26, 2025
HomeStatistics TutorialRHow to Use str_count in R (With Examples)

How to Use str_count in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 #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 #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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories