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
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
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
.
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