Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding function names from ls() results - to find a variable name more quickly

Tags:

r

When we have defined tens of functions - probably to develop a new package - it is hard to find out the name of a specific variable among many function names through ls() command.

In most of cases we are not looking for a function name - we already know they exist - but we want to find what was the name we assigned to a variable.

Any idea to solve it is highly appreciated.

like image 726
Ali Avatar asked Dec 07 '22 11:12

Ali


1 Answers

If you want a function to do this, you need to play around a bit with the environment that ls() looks in. In normal usage, the implementation below will work by listing objects in the parent frame of the function, which will be the global environment if called at the top level.

lsnofun <- function(name = parent.frame()) {
    obj <- ls(name = name)
    obj[!sapply(obj, function(x) is.function(get(x)))]
}

> ls()
[1] "bar"           "crossvalidate" "df"           
[4] "f1"            "f2"            "foo"          
[7] "lsnofun"       "prod"         
> lsnofun()
[1] "crossvalidate" "df"            "f1"           
[4] "f2"            "foo"           "prod"

I've written this so you can pass in the name argument of ls() if you need to call this way down in a series of nested function calls.

Note also we need to get() the objects named by ls() when we test if they are a function or not.

like image 134
Gavin Simpson Avatar answered Jan 18 '23 02:01

Gavin Simpson