1

I would like to be able to subset the list of objects in my Global Environment by class.

i.e. from the list created by running

ls()

I would like to be able to make a shorter list that only has the names of the objects that belong to specific class e.g. xts or POSIXlt

Thanks in advance

h.l.m
  • 13,015
  • 22
  • 82
  • 169
  • http://stackoverflow.com/questions/5158830/identify-all-objects-of-given-class-for-further-processing – Chase Mar 05 '12 at 03:26

2 Answers2

3

This is a slight twist to the above which uses inherits to inspect the object:

objs =  mget(ls(envir=.GlobalEnv), envir=.GlobalEnv)
names(Filter(function(i) inherits(i, "lm"), objs))

The function(i) inherits(i, "lm") can be adjusted as you want.

jverzani
  • 5,600
  • 2
  • 21
  • 17
2

You could retrieve ls() and check the class of everything. It may not be particularly efficient though, as it does the filtering after ls() and not within.

# populate global environment with some vars.
rm(list=ls())
a <- 1
b <- 2
c <- 'foo'
d <- 'asdf'
lst <- ls()
# return everything 'numeric':
lst[sapply(lst,function(var) any(class(get(var))=='numeric'))]
# 'a' 'b'

The get(var) gets the variable corresponding to the string in var, so if var is "a" then get(var) retrieves 1 (being the value of variable a).

As @VincentZoonekynd notes below - it is possible for objects to have multiple classes. Soo class(some_xts_object) is c("xts","zoo") -- the above method will return some_xts_object if you search for xts objects, but also if you search for zoo objects.

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
  • That assumes that objects belong to only one class. This is not always the case: for instance, `xts` objects are also of class `zoo`. – Vincent Zoonekynd Mar 05 '12 at 02:55
  • Oh, I didn't realise you could have multiple classes. I'll add an `any(class(..)=='numeric')` (`class(some_xts_object)` gives c('xts','zoo'); may this be relied upon?) – mathematical.coffee Mar 05 '12 at 02:58
  • `class(some_xts_object)` will always contain at least `xts` and `zoo`, but could contain more. I usually use `"xts" %in% class(u)`, which is equivalent to your suggestion. – Vincent Zoonekynd Mar 05 '12 at 03:03