Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

r - Identify all objects of given class for further processing

Assume you are working with a large working environment and you aren't great about keeping up with your environment variables, or you have some process that generates a lot objects automatically. Is there a way to scan your ls() to identify all objects that have a given class? Consider the following simple example:

#Random objects in my environment
x <- rnorm(100)
y <- rnorm(100)
z <- rnorm(100)

#I estimate some linear models for fun.
lm1 <- lm(y ~ x)
lm2 <- lm(y ~ z)
lm3 <- lm(y ~ x + z)

#Is there a programmatic way to identify all objects in my environment 
#that are of the "lm" class? Or really, any arbitrary class?
outList <- list(lm1, lm2, lm3)

#I want to look at a bunch of plots for all the lm objects in my environment.
lapply(outList, plot)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the class function:

Models <- Filter( function(x) 'lm' %in% class( get(x) ), ls() )
lapply( Models, function(x) plot( get(x) ) )

(Modified slightly to handle situations where objects can have multiple classes, as pointed out by @Gabor in the comments).

Update. For completeness, here is a refinement suggested by @Gabor's comment below. Sometimes we may want to only get objects that are of class X but not class Y. Or perhaps some other combination. For this one could write a ClassFilter() function that contains all of the class filterling logic, such as:

ClassFilter <- function(x) inherits(get(x), 'lm' ) & !inherits(get(x), 'glm' )

Then you get the objects that you want:

Objs <- Filter( ClassFilter, ls() )

Now you can process the Objs whatever way you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...