countPatternMatches.R (812B)
1 #' Count how many matches are generated by each pattern. 2 #' 3 #' @param X A character vector where matches are sought. 4 #' @param patterns A vector of regular expression patterns. 5 #' 6 #' @return A integer vector of same length as \code{patterns} with a count of 7 #' matches. 8 #' 9 #' @details This is meant to be useful when developing a vector of regexes to 10 #' apply to text. Unlike \code{patternappy()}, which only finds the first 11 #' regex that matches each element of text, a text element here can match 12 #' multiple regexes. Therefore, the sum of the returned vector may not equal 13 #' the length of the input \code{X}. 14 #' @export 15 countPatternMatches <- function(X, patterns) { 16 return(vapply(patterns, 17 function(pattern) length(grep(pattern, X)), 18 integer(1))) 19 }