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

Filter vector elements containing and not containing multiple strings

Based on code from this link, we could find file names containing multiple strings:

allpatterns <- function(fnames, patterns) {
  i <- sapply(fnames, function(fn) all(sapply(patterns, grepl, fn)) )
  fnames[i]
}

filenames <- c("foo.txt", "bar.R", "foo_quux.py", "quux.c", "quux.foo",
               "foo_bar", "bar.foo.cpp", "foo_bar_quux", "quux_foo.bar", "nothing")

allpatterns(filenames, c("foo", "bar"))
# [1] "foo_bar"      "bar.foo.cpp"  "foo_bar_quux" "quux_foo.bar"

Now I’d like to go further by adding a condition not contain certain strings, for example I hope to filter file names which containing foo, bar and not containing cpp, quux, which will gives following result:

 # [1] "foo_bar"

How could I achieve that by modifying code above?

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

>Solution :

"foo" OR "bar" without "cpp" and "quux":

filenames[grepl("foo|bar",filenames)&!grepl("cpp|quux",filenames)]
[1] "foo.txt" "bar.R"   "foo_bar"

"foo" AND "bar" without "cpp" and "quux":

filenames[grepl("(?=.*foo)(?=.*bar)",filenames,perl = T)&!grepl("cpp|quux",filenames)]
[1] "foo_bar"
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