Set the function environment in relation to the environment of the calling environment (parent.frame) from inside the function

I am still struggling with the R area and environment. I would like to be able to create simple helper functions that are called from my β€œcore” functions, which can directly refer to all the variables in these core functions, but I do not want to define helper functions in each of my core 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 
+6
source share
3 answers

Well, a function cannot change it by default, but you can use eval to run code in another environment. I'm not sure if this matches elegance exactly, but this should work:

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

If you declare that each of your functions will be used with dynamic coverage at the beginning of the main function, as shown in the example below, it will work. Using the helpFunction asked in the question:

 mainfunction <- function(importantVar1) { # declare each of your functions to be used with dynamic scoping like this: environment(helpFunction) <- environment() helpFunction() } mainfunction(importantVar1=3) 

It is not possible to change the source of the auxiliary functions themselves.

By the way, you might want to take a look at the link classes or the proto-package, because it seems that you are trying to do object-oriented programming through the back door.

+12
source

Path R will pass the arguments to the function:

 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 

Edit, since you are claiming that it is "not working":

 helpFunction<-function(importantVar1){ importantVar1+1 } mainFunction<-function(importantVar1){ helpFunction(importantVar1) } mainFunction(importantVar1=3) #[1] 4 
+2
source

Source: https://habr.com/ru/post/969908/


All Articles