Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pulling all objects in the global environment that have specific attributes

Tags:

r

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

like image 633
Brandon Bertelsen Avatar asked Dec 21 '22 14:12

Brandon Bertelsen


1 Answers

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)
like image 110
Richie Cotton Avatar answered Jan 31 '23 07:01

Richie Cotton