Here,
a<-c("Look at the sky", "Sun is bright", "cloudy day")
b<-c("sky", "day")
I want to subset a based on b. My preferred answer is:
"Look at the sky", "cloudy day"
How to do this in R?
You can match a against all terms in b with sapply
sapply(b, grepl, a)
sky day
[1,] TRUE FALSE
[2,] FALSE FALSE
[3,] FALSE TRUE
Then you collapse all rows with apply and subset a.
a[apply(sapply(b, grepl, a), 1, any)]
[1] "Look at the sky" "cloudy day"
Create a combined regexp pattern
paste(b, collapse="|")
[1] "sky|day"
and grep with it
a[grepl(paste(b, collapse="|"), a)]
[1] "Look at the sky" "cloudy day"
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