str_count

The function stringr::str_counts() counts the number of matches to a pattern/regular expression within each element of a string vector.

Tidyverse reference page

Count

Prior to using the function create a vector of strings.

#Create vector of strings
vec <- c("Rose", "Thistle", "Leek", "Shamrock")
#View vector
vec
[1] "Rose"     "Thistle"  "Leek"     "Shamrock"

You can specify a string pattern to be used for detection.

#Count instances of s
vec |> stringr::str_count("s")
[1] 1 1 0 0
#Count instances of e
vec |> stringr::str_count("e")
[1] 1 1 2 0

The function is case-sensitive. “R” will detect “Rose” but not “shamrock”.

#Detect the letter R
vec |> stringr::str_count("R")
[1] 1 0 0 0

The function works with various regular expressions.

#Detect the letter R or r
vec |> stringr::str_count("[Rr]")
[1] 1 0 0 1
#Count number of vowels
vec |> stringr::str_count("[aeiou]")
[1] 2 2 2 2

Count number of letters between A-M (inclusive), lower or upper case.

#Count number of vowels
vec |> stringr::str_count("[A-Ma-m]")
[1] 1 4 4 5