dataquerent
dataquerent

Reputation: 267

I want to have a list of all the functions in my R workspace that works like the objects() command

I love working with R functions, so my workspace accumulates a lot of functions.

However, the "objects()" command seems to return strings that name my objects instead of the objects themselves. So when I have a function named "barchart00", it shows up with the objects() command, and if I test its type, it is detectable as a function, as the following code shows:

is.function(barchart00) [1] TRUE

> objects()
[1] "barchart00"  

> OL<-objects()
> OL
[1] "barchart00"  

> is.function(OL[1])
[1] FALSE

This wouldn't be a problem if I had just one or two or three functions. But in practice I have dozens of functions, AND dozens of objects that are not functions, and I want to get a list of functions that's just as convenient as the list of objects returned by objects().

My first thought was that if objects() returned a list of actual objects, I could just go through that list and test for function status. But in fact, objects() seems to return a list of strings that are the names of my objects, not the objects themselves.

Any constructive advice would be greatly appreciated. Thanks.

...Hong Ooi answered the question but I can't mark it as answered for another eight hours.

lsf.str() is the syntax I was looking for.

All credit should go to Hong Ooi.

https://stackoverflow.com/users/474349/hong-ooi

Thanks, Hong Ooi.

Upvotes: 1

Views: 286

Answers (1)

Carl Witthoft
Carl Witthoft

Reputation: 21532

lsf.str looks like a fine answer. If you'd like a more general tool, here's one from my (horn-tooting here) cgwtools package. You can get a list of any particular type of object in your environment (not just closures).

lstype <-  function(type='closure'){
#simple command to get only one type of object in current environment
# Note: if you foolishly create variables named 'c' ,'q' ,'t' or the like,
# this will fail because typeof finds the builtin function first
        inlist<-ls(.GlobalEnv)
        if (type=='function') type <-'closure'
        typelist<-sapply(sapply(inlist,get),typeof)
        return(names(typelist[typelist==type]))
}

Upvotes: 1

Related Questions