[R] Question about function scope

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Tue Oct 30 21:18:51 CET 2018


Here's another modification to your code that also works.  It's a lot 
uglier, but will allow bar1 and bar2 to be used in multiple functions, 
not just foo.

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

bar2 <- function(env){
   env$x <- 2
   env$y <- 2
   env$z <- 2
   with(env, 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(environment())
   if (c==2) bar2(environment())

   # 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)

Duncan Murdoch




More information about the R-help mailing list