Mahmoud
Mahmoud

Reputation: 401

grepl on two vectors element by element

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 

Upvotes: 5

Views: 1204

Answers (4)

NelsonGon
NelsonGon

Reputation: 13309

We can use also purrr:

purrr::map2(c("bc","23","a2"),c("abcd","1234","zzzz"),
            function(x,y) grepl(x,y))
[[1]]
[1] TRUE

[[2]]
[1] TRUE

[[3]]
[1] FALSE

If you want to stay with base:

   unlist(Map(function(x,y) grepl(x,y), my_list[[1]],my_list[[2]]))
   bc    23    a2 
 TRUE  TRUE FALSE 

Upvotes: 2

nicola
nicola

Reputation: 24480

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.

Upvotes: 5

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

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 

Upvotes: 5

MatthewR
MatthewR

Reputation: 2770

Try the or operator

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

Upvotes: -1

Related Questions