Learn R Programming

berryFunctions (version 1.22.13)

count: count string occurrences

Description

count how often a certain string occurs, summing over a vector

Usage

count(pattern, x, ...)

Value

single integer

Arguments

pattern

character string (can have regex)

x

charstring (vector)

...

Further arguments passed to gregexpr

Author

Berry Boessenkool, berry-b@gmx.de, Jan 2025

Examples

Run this code
vec210 <- c("with abc + abc + ab", "also abcde", "no alphabet")
vec021 <- c("no alphabet", "this has abcabc + ab", "also abcde")
vec000 <- c("this has no", "alphabet", "at all")
vec4 <-     "this has abc and abcabcabc"
stopifnot(count("abc", vec210) == 3)
stopifnot(count("abc", vec021) == 3)
stopifnot(count("abc", vec000) == 0)
stopifnot(count("abc", vec4  ) == 4)

# vectorized count:
vec <- c(a="xx", b="xabx", c="xabxab", d="abxx", e="abxxabxxabxxab", f="axbx")
sapply(gregexpr("ab", vec), function(x) sum(x>0))

Run the code above in your browser using DataLab