Joseph Doob
Joseph Doob

Reputation: 173

How can I return all functions defined within a function?

I want to return all functions I have defined within a function.

I know ls() can be used to return names of my functions, but I need to return a list of the functions defined in the original function's body.

For example, my function might look like

primaryFunction<-function(){
    a<-function(){return (2)} 
    b<-function(){return (3)} 
    return(?)} 

where return(?) is supposed to return a list containing the functions a,b.

Upvotes: 2

Views: 196

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545598

Normally I’d list them all separately to be explicit:

primary_function = function () {
    a = function () 2
    b = function () 3
    list(a = a, b = b)
}

But you can abbreviate if there are many:

primary_function = function () {
    a = function () 2
    b = function () 3
    as.list(environment())
}

(You could also return the environment itself instead of copying it into a list.)

Note that this will return all local symbols. If you have non-function symbols and want to return only functions, instead do

primary_function = function () {
    a = function () 2
    b = function () 3
    mget(lsf.str())
}

Also note that your code contains errors since in R return isn’t a statement, it’s a function call, which aborts the current function execution. As such, you need to write it with parentheses (e.g. return(2), not return 2), and their use is redundant here: R always returns the last value of a function’s execution. That’s why I omitted them. I only use return to signal an early exit.

Upvotes: 4

Related Questions