Let's say I have a list of objects in the global environment. How would I pull only those that have a specific attribute set?
x1 <- 1:10
x2 <- 1:10
x3 <- 1:10
x4 <- 1:10
x5 <- 1:10
attr(x1, "foo") <- "bar"
attr(x5, "foo") <- "bar"
How do I pull x1 and x5 based on the fact that they have the attribute "foo" as "bar"?
A couple of variations on Ramnath's answer.
For getting 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 intention of the code slightly clearer. (Though it does the same thing underneath the bonnet.)
Filter(function(x) attr(x, "foo") == "bar", all)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With