Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use grepl in every row?

Tags:

r

grepl

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.

like image 676
PhiSo Avatar asked Dec 05 '22 13:12

PhiSo


1 Answers

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])
}
like image 125
Ben Bolker Avatar answered Dec 14 '22 23:12

Ben Bolker