h.l.m
h.l.m

Reputation: 13475

R sub-setting the list of objects in the global environment by class

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

Upvotes: 1

Views: 1616

Answers (2)

jverzani
jverzani

Reputation: 5700

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.

Upvotes: 3

mathematical.coffee
mathematical.coffee

Reputation: 56935

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.

Upvotes: 2

Related Questions