我仍然在与R的作用域和环境作斗争。我希望能够构建简单的辅助函数,从我的"主"函数中调用,可以直接引用这些主要函数中的所有变量-但我不想在每个主要函数中定义辅助函数。
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
如果您在mainfunction的开头声明每个函数使用动态作用域,如下面的示例所示,它将工作。使用问题中定义的helpFunction
:
mainfunction <- function(importantVar1) {
# declare each of your functions to be used with dynamic scoping like this:
environment(helpFunction) <- environment()
helpFunction()
}
mainfunction(importantVar1=3)
不需要修改辅助函数本身的源代码。
顺便说一下,你可能想看看参考类或原型包,因为它看起来好像你试图通过后门做面向对象的编程。
函数不能改变它的默认环境,但是您可以使用eval
在不同的环境中运行代码。我不确定这是否符合优雅的标准,但这应该可以工作:
helpFunction<-function(){
eval(quote(importantVar1+1), parent.frame())
}
mainFunction<-function(importantVar1){
return(helpFunction())
}
mainFunction(importantVar1=3)
R的方式是传递函数参数:
helpFunction<-function(x){
#you can also use importantVar1 as argument name instead of x
#it will be local to this helper function, but since you pass the value
#it will have the same value as in the main function
x+1
}
mainFunction<-function(importantVar1){
helpFunction(importantVar1)
}
mainFunction(importantVar1=3)
#[1] 4
编辑,因为你声称"不工作":
helpFunction<-function(importantVar1){
importantVar1+1
}
mainFunction<-function(importantVar1){
helpFunction(importantVar1)
}
mainFunction(importantVar1=3)
#[1] 4