Search code examples
rfunctionenvironment-variablesscoping

Set a functions environment to that of the calling environment (parent.frame) from within function


I am still struggling with R scoping and environments. I would like to be able to construct simple helper functions that get called from my 'main' functions that can directly reference all the variables within those main functions - but I don't want to have to define the helper functions within each of my main functions.

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

Solution

  • Well, a function cannot change it's default environment, but you can use eval to run code in a different environment. I'm not sure this exactly qualifies as elegant, but this should work:

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