I'm trying to search for a pattern in a text using grepl
. The problem is that my pattern is a list of names and my text is also a list of texts of the same length. I would like to build a loop that goes over each row and search for a given name in the corresponding text.
edit for clarity
So for example, in this data:
pat <- c("mary", "john", "anthony")
text <- c("This is a long text about anthony", "This is another long text about john", "This is a final text about mary").
I would like search "mary"
in the first text, and then "john"
in the second, and finally "anthony"
in the third one.
pat <- c("mary", "john", "anthony")
text <- c("This is a long text about anthony", "This is another long text about john", "This is a final text about mary")
The Map
or mapply
functions will do this:
Map(grepl,pat,text)
(this returns a list, which you can unlist
)
or
mapply(grepl,pat,text)
(automatically simplifies) or
n <- length(pat)
res <- logical(n)
for (i in seq(n)) {
res[i] <- grepl(pat[i],text[i])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With