Identify all objects of given class for further processing

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.

Leave a Comment