Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grepl on two vectors element by element

Tags:

r

grepl

I'd like to apply grepl on two vectors to see if elements of the first vector are available in the corresponding elements of the second vector. For example

grepl(c("bc","23","a2"),c("abcd","1234","zzzz"))

And since bc is in abcd, 23 is in 1234 and a2 is not in zzzz, I'd like to get TRUE TRUE FALSE. But, instead here is what I get:

[1]  TRUE FALSE FALSE
Warning message:
In grepl(c("bc", "23", "a2"), c("abcd", "1234", "zzzz")) :
argument 'pattern' has length > 1 and only the first element will be used 
like image 331
Mahmoud Avatar asked May 19 '19 05:05

Mahmoud


2 Answers

We can try using mapply here:

fun <- function(x, y) {
    grepl(x, y)
}

mapply(fun, c("bc","23","a2"), c("abcd","1234","zzzz"))

  bc    23    a2 
TRUE  TRUE FALSE 
like image 176
Tim Biegeleisen Avatar answered Oct 26 '22 23:10

Tim Biegeleisen


The stringr package (which relies on stringi) offers naturally vectorized regex functions:

require(stringr)
str_detect(string=c("abcd","1234","zzzz"),pattern=c("bc","23","a2"))
#[1]  TRUE  TRUE FALSE

Notice that the order of arguments is different with respect to grep.

like image 21
nicola Avatar answered Oct 26 '22 22:10

nicola