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

How to filter a data frame where only part of the string matches any item in a vector

I want to filter my data frame based on whether one column contains text that appears in a vector. The string in each cell of the column is quite long, and I only need the vector item to appear within the string.

I can do this for a single reference e.g.

library(dplyr)
starwars %>%
  filter(grepl("at", name))

But what if I want to use a vector of references?

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

attributes = c("at", "oo", "un")

>Solution :

Use paste with collapse = "|" to detect multiple patterns.

attributes = c("at", "oo", "un")
#paste(attributes, collapse = "|")
#[1] "at|oo|un"

starwars %>%
  filter(grepl(paste(attributes, collapse = "|"), name))

Another way, if you don’t want to go by paste:

starwars %>%
  filter(sapply(name, \(x) any(sapply(attributes, str_detect, string = x))))
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