search string in data frame using another dataframe and grepl

Viewed 293

I need to filter a data frame by column using another dataframe but because the matches could not be exact I guess using grepl would be a way.

the following code might exemplify:

A <- data.frame(X=c("RRT","FGT","UTX","GRW"),Y=c(5,6,9,4))

B <- data.frame(Z=c("PPL","FG","RT","UTX"))

A %>% filter(.,grepl("RT",X))

# the result using a single match
X Y
RRT 5

##desired result

A %>% filter(.,grepl(B,A$X))

A.X  A.Y
RRT  5
FGT  6
UTX  9

What is the best way to accomplish that?

3 Answers

What about this?

> A %>%
+   filter(colSums(outer(B$Z, X, Vectorize(grepl))) > 0)
    X Y
1 RRT 5
2 FGT 6
3 UTX 9

create a regex-pattern based on B$Z, and filter on that

A[grepl(paste0(B$Z, collapse = "|"), A$X), ]

Using str_detect

library(dplyr)
library(stringr)
A %>% 
   filter(str_detect(X, str_c(B$Z, collapse = "|")))
    X Y
1 RRT 5
2 FGT 6
3 UTX 9
Related