[R] Question about function scope
Sebastien Bihorel
@eb@@t|en@b|hore| @end|ng |rom cogn|gencorp@com
Tue Oct 30 21:23:46 CET 2018
That's cool! I think this solution would fit better with what my intended setup.
Thanks a lot
----- Original Message -----
From: "Duncan Murdoch" <murdoch.duncan using gmail.com>
To: "Sebastien Bihorel" <sebastien.bihorel using cognigencorp.com>, r-help using r-project.org
Sent: Tuesday, October 30, 2018 4:18:51 PM
Subject: Re: [R] Question about function scope
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