Find rows where one column string is in another column using dplyr in R
We can do this with Map
df[mapply(grepl, df$A, df$B),]
# A B
#1 cat cat in the cradle
#3 boy boy mmets world
Update
Using tidyverse
, similar option would be purrr::map2
with stringr::str_detect
library(tidyverse)
df %>%
filter(map2_lgl(B, A, str_detect))
# A B
#1 cat cat in the cradle
#2 boy boy mmets world
data
df <- data.frame(A, B, stringsAsFactors=FALSE)
You can either apply the function to both vectors using Map
or iterate through the row using sapply
df %>%
filter(unlist(Map(function(x, y) grepl(x, y), A, B)))
A B
1 cat cat in the cradle
2 boy boy mmets world
df %>%
filter(sapply(1:nrow(.), function(i) grepl(A[i], B[i])))
A B
1 cat cat in the cradle
2 boy boy mmets world