Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check whether a string appears in another in R

I’ve got a tibble containing sentences like that :

df <- tibble(sentences = c("Bob is looking for something", "Adriana has an umbrella", "Michael is looking at..."))

And another containing a long list of names :

names <- tibble(names = c("Bob", "Mary", "Michael", "John", "Etc."))

I would like to see if the sentences contain a name from the list and add a column to indicate if this is the case and get the following tibble :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

wanted_df <- tibble(sentences = c("Bob is looking for something", "Adriana has an umbrella", "Michael is looking at..."), check = c(TRUE, FALSE, TRUE))

So far I’ve tried that, with no success :

df <- df %>%
mutate(check = grepl(pattern = names$names, x = df$sentences, fixed = TRUE))

And also :

check <- str_detect(names$names %in% df$sentences)

Thanks a lot for any help 😉

>Solution :

You should form a single regex expression in grepl:

df %>% 
  mutate(check = grepl(paste(names$names, collapse = "|"), sentences))

# A tibble: 3 × 2
  sentences                    check
  <chr>                        <lgl>
1 Bob is looking for something TRUE 
2 Adriana has an umbrella      FALSE
3 Michael is looking at...     TRUE 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading