简体   繁体   English

如何返回函数中定义的所有函数?

[英]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. 我知道ls()可用于返回函数名称,但我需要返回原始函数主体中定义的函数列表。

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. 其中return(?)应该返回包含函数a,b的列表。

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. 还要注意,您的代码包含错误,因为在R return中不是语句,而是函数调用 ,它将中止当前函数执行。 As such, you need to write it with parentheses (eg return(2) , not return 2 ), and their use is redundant here: R always returns the last value of a function's execution. 因此,您需要在括号中写上它(例如return(2) ,而不是return 2 ),在这里使用它们是多余的:R总是返回函数执行的最后一个值。 That's why I omitted them. 这就是为什么我忽略了它们。 I only use return to signal an early exit. 我只使用return表示提前退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM