从函数内部将函数环境设置为调用环境(parent.frame)的函数环境

Cha*_*lie 13 r function environment-variables scoping

我仍然在努力寻找R范围和环境.我希望能够构造简单的辅助函数,这些函数可以从我的'main'函数中调用,这些函数可以直接引用这些主函数中的所有变量 - 但是我不想在每个main函数中定义辅助函数功能.

helpFunction<-function(){
#can I add a line here to alter the environment of this helper function to that of the calling function?
return(importantVar1+1)
}

mainFunction<-function(importantVar1){
return(helpFunction())
}

mainFunction(importantVar1=3) #so this should output 4
Run Code Online (Sandbox Code Playgroud)

G. *_*eck 21

如果您声明要在main函数开头使用动态范围的每个函数,如下例所示,它将起作用.使用helpFunction问题中定义的:

mainfunction <- function(importantVar1) {

    # declare each of your functions to be used with dynamic scoping like this:
    environment(helpFunction) <- environment()

    helpFunction()
}

mainfunction(importantVar1=3)
Run Code Online (Sandbox Code Playgroud)

辅助函数本身的来源不需要修改.

顺便说一下,你可能想要查看引用类或proto包,因为它似乎试图通过后门进行面向对象的编程.


MrF*_*ick 6

好吧,函数不能改变它的默认环境,但是你可以用它eval来在不同的环境中运行代码.我不确定这完全符合优雅,但这应该有效:

helpFunction<-function(){
    eval(quote(importantVar1+1), parent.frame())
}

mainFunction<-function(importantVar1){
    return(helpFunction())
}

mainFunction(importantVar1=3)
Run Code Online (Sandbox Code Playgroud)