count: count string occurrences

View source: R/count.R

countR Documentation

count string occurrences

Description

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

Usage

count(pattern, x, ...)

Arguments

pattern

character string (can have regex)

x

charstring (vector)

...

Further arguments passed to gregexpr

Value

single integer

Author(s)

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

Examples

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


berryFunctions documentation built on Aug. 8, 2025, 6:18 p.m.