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?
>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))