stringr::str_count()
get_help()
docs
The str_count()
function is part of the {stringr}
package, which is part of the {tidyverse}
.
We use the str_count()
function to count the number of times a given smaller string or regular expression (a special type of pattern-matching string) appears in a larger string.
All {stringr}
functions (and R
itself) are case sensitive, which means uppercase and lowercase letters are viewed as different characters. In other words, searching for “A” will not match “a”, and searching for “a” will not match “A.”
To use this function, you need to either first load the {stringr}
library, or always use the function with stringr::str_count()
notation.
# Load the library
library(stringr)
# Or, load the full tidyverse:
library(tidyverse)
# Or, use :: notation
::str_count() stringr
::str_count("string to count observations in", "substring to look for in bigger string")
stringr
::str_count(c("array", "of", "strings", "to", "count", "observations", "in"),
stringr"substring to look for in each string in the array")
The examples use the variables shown below, as well as the carnivores
dataset. Learn more about the carnivores
with get_help("carnivores")
.
# Show all variables and datasets used in examples:
# A single string
single_sentence## [1] "No doubt about the way the wind blows."
# An array of strings
fruits## [1] "kiwi fruit" "pomelo" "goji berry" "persimmon" "mulberry" "raspberry"
# A tibble
carnivores## # A tibble: 9 × 4
## name genus awake brainwt
## <chr> <fct> <dbl> <dbl>
## 1 Arctic fox Vulpes 11.5 0.0445
## 2 Cheetah Acinonyx 11.9 NA
## 3 Dog Canis 13.9 0.07
## 4 Gray seal Haliochoerus 17.8 0.325
## 5 Jaguar Panthera 13.6 0.157
## 6 Lion Panthera 10.5 NA
## 7 Northern fur seal Callorhinus 15.3 NA
## 8 Red fox Vulpes 14.2 0.0504
## 9 Tiger Panthera 8.2 NA
# Count the number of times the substring "ou" appears in `single_sentence`
str_count(single_sentence, "ou")
## [1] 2
# Count the number of times the capital letter "A" appears in `single_sentence`
str_count(single_sentence, "A")
## [1] 0
# Count the number of times the letter "o" appears in _each string_ in the array `fruits`
# The result is an array that counts each string's number of "o"s
str_count(fruits, "o")
## [1] 0 2 1 1 0 0
# Count the number of times the letter "a" appears in each genus in carnivores
str_count(carnivores$genus, "a")
## [1] 0 0 1 1 2 2 1 0 2
# Use dplyr::mutate() to create a new column in carnivores containing counts of the letter "a" in `genus`
%>%
carnivores ::mutate(number_a_in_genus = str_count(genus, "a")) dplyr
## # A tibble: 9 × 5
## name genus awake brainwt number_a_in_genus
## <chr> <fct> <dbl> <dbl> <int>
## 1 Arctic fox Vulpes 11.5 0.0445 0
## 2 Cheetah Acinonyx 11.9 NA 0
## 3 Dog Canis 13.9 0.07 1
## 4 Gray seal Haliochoerus 17.8 0.325 1
## 5 Jaguar Panthera 13.6 0.157 2
## 6 Lion Panthera 10.5 NA 2
## 7 Northern fur seal Callorhinus 15.3 NA 1
## 8 Red fox Vulpes 14.2 0.0504 0
## 9 Tiger Panthera 8.2 NA 2