[R] Question about function scope

Sebastien Bihorel @eb@@tien@bihorel @ending from cognigencorp@com
Tue Oct 30 20:56:42 CET 2018


Hi,

>From the R user manual, I have a basic understanding of the scope of function evaluation but have a harder time understanding how to mess with environments.

My problem can be summarized by the code shown at the bottom:
- the foo function performs some steps including the assignment of default values to 3 objects: x, y, z
- at some point, I would like to call either the bar1 or bar2 function based upon the value of the c argument of the foo function. These functions assign different values to the x, y, z variables.
- then foo should move on and do other cool stuff

Based upon default R scoping, the x, y, and z variables inside the bar1 and bar2 functions are not in the same environment as the x, y, and z variables created inside the foo function.

Can I modify the scope of evaluation of bar1 and bar2 so that x, y, and z created inside the foo function are modified?

PS: 
- I know about "<<-" but, in my real code (which I cannot share, sorry), foo is already called within other functions and x, y, and z variables do not exist in the top-level environment and are not returned by foo. So "<<-" does not work (per manual: " Only when <<- has been used in a function that was returned as the value of another function will the special behavior described here occur. ")
- In my real example, I have a few dozens of variables to transform in bar1 and bar2 so exporting a list bundling all the transform values then dispatching them in foo does not seem practical
- currently, my best solution is to save the inner part of bar1 and bar2 in separate scripts and sourcing them in foo (that does not seem elegant...)
- also, I know that, theoretically, I could put the content of bar1 and bar2 directly in foo, but as the number of cases handled by foo grows, the code will become way too long and hardly manageable.

Thanks for your help


######################################

bar1 <- function(){
  x <- 1
  y <- 1
  z <- 1
  cat(sprintf('bar1: x=%d, y=%d, z=%d\n', x, y, z))
}

bar2 <- function(){
  x <- 2
  y <- 2
  z <- 2
  cat(sprintf('bar2: x=%d, y=%d, z=%d\n', x, y, z))
}

foo <- function(a=1, b=2, c=0){

  # some setup code
  dummy <- a + b
  x <- y <- z <- 0

  # here is my scope problem
  if (c==1) bar1()
  if (c==2) bar2()

  # some more code
  cat(sprintf('foo: x=%d, y=%d, z=%d\n', x, y, z))
  
}

foo(c=0)
foo(c=1)
foo(c=2)



More information about the R-help mailing list