Pulling all objects in a global environment with specific attributes

Say I have a list of objects in a global environment. How can I pull out only those that have a specific set of attributes?

x1 <- 1:10 x2 <- 1:10 x3 <- 1:10 x4 <- 1:10 x5 <- 1:10 attr(x1, "foo") <- "bar" attr(x5, "foo") <- "bar" 

How to pull x1 and x5 based on the fact that they have the attribute "foo" as "bar"?

+4
source share
2 answers

Here is one way to do it.

 # collect all objects in global environment all = lapply(ls(), get) # extract objects with attribute = "bar" bar = all[lapply(all, attr, "foo") == "bar"] 
+5
source

Several answers of Ramnath.

To get multiple objects, it is preferable to use mget instead of get with lapply .

 all <- mget(ls(), envir = globalenv()) 

You can use Filter to filter the list of variables. I think this makes the code more clear. (Although he does the same under the hood.)

 Filter(function(x) attr(x, "foo") == "bar", all) 
+4
source

All Articles