R: Count occurrences of character in string

Problem

In GNU R, you have an arbitrary string s and want to count how often a given character occurs in s.

Solution

There might be a more efficient way, but substituting all occurrences in s by the empty string and counting the length difference works – the concept also works for substrings if they are guaranteed not to overlap.

# The string to search in
> s <- "aababac"
# The character to search for
> p <- "a"
# Replace all occurrences by the empty string - note that gsub uses regular expressions, so escape p accordingly
> s2 <- gsub(p,"",s) # Count the length difference
> numOcc <- nchar(s) - nchar(s2) # numOcc now contains the number of occurrences of p in s

Or simply use this function

countCharOccurrences <- function(char, s) {
    s2 <- gsub(char,"",s)
    return (nchar(s) - nchar(s2))
}