R/countPatternMatches.R

#' Count how many matches are generated by each pattern.
#' 
#' @param X A character vector where matches are sought.
#' @param patterns A vector of regular expression patterns.
#'   
#' @return A integer vector of same length as \code{patterns} with a count of 
#'   matches.
#'   
#' @details This is meant to be useful when developing a vector of regexes to 
#'   apply to text. Unlike \code{patternappy()}, which only finds the first 
#'   regex that matches each element of text, a text element here can match 
#'   multiple regexes. Therefore, the sum of the returned vector may not equal 
#'   the length of the input \code{X}.
#' @export
countPatternMatches <- function(X, patterns) {
  return(vapply(patterns, 
                function(pattern) length(grep(pattern, X)), 
                integer(1)))
}
eamoncaddigan/patternapply documentation built on May 15, 2019, 7:27 p.m.