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 search for two patterns in logical AND fashion with regex in R?

I’m trying to get a list of objects from my global environment that contains items that have a single character at a certain position, and also contain another string at the end of their name. So I only want the matches where both of those conditions are true.

This is what it looks like when only doing the former:

    pattern<-grep("^.{3}a",names(.GlobalEnv),value=TRUE)
    plot_list<-do.call("list",mget(pattern))

I would now like to add the latter condition to the pattern as well, so that it doesn’t yield all object with "a" on position 3, but only those that also end with "plot". What’s the easiest way to do that?

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 :

Assuming you want objects with a as the 3rd character which also end in plot, you should use the regex pattern ^.{2}a.*plot$:

pattern <- grep("^.{2}a.*plot$", names(.GlobalEnv), value=TRUE)
plot_list <- do.call("list", mget(pattern))
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