Reputation: 171
I have three strings which contain what , when , why as given below
Is there a way to list out all string which contain the given pattern.
First i detected for the pattern and then counted the number of True values
e<-str_detect(c, "What")
length(e[e == TRUE])
I expect the output in the way
Number of string contain What: 02
Number of String contain when : 01
Number of String contain why : 01
Upvotes: 1
Views: 439
Reputation: 389265
We could create a vector to search for and use sapply
to find if it is present in a string
vals <- colSums(sapply(tags, function(x)
grepl(paste0("\\b",x, "\\b"), strings, ignore.case = TRUE)))
vals
#what when why
# 2 1 1
ignore.case
ignores the case so "What"
and "what"
is the same.
Word boundary ("\\b"
) is added for each tag
so that "what"
does not match with "whatever"
.
data
strings <- c("What is your name", "When and why should you run for high speed",
"What is your father name ")
tags <- c("what", "when", "why")
Upvotes: 3