Skip to content
Prev 377169 / 398502 Next

Question about function scope

Thanks a lot Eric, 

I think you are on the same page as Duncan (at least with his 2nd option). I will definitively explore this. 


From: "Eric Berger" <ericjberger at gmail.com> 
To: "Duncan Murdoch" <murdoch.duncan at gmail.com> 
Cc: "Sebastien Bihorel" <sebastien.bihorel at cognigencorp.com>, "R mailing list" <r-help at r-project.org> 
Sent: Tuesday, October 30, 2018 4:17:30 PM 
Subject: Re: [R] Question about function scope 

Hi Sebastien, 
I like Duncan's response. An alternative approach is to pass around environments, as in the following: 

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

foo <- function(a=1, b=2, c=0, e){ 
# some setup code 
dummy <- a + b 
e$x <- e$y <- e$z <- 0 
# here is my scope problem 
if (c==1) bar1(e) 
if (c==2) bar2(e) 
# some more code 
cat(sprintf('foo: x=%d, y=%d, z=%d\n', e$x, e$y, e$z)) 
} 

e <- new.env() 
e$x <- NA 
e$y <- NA 
e$z <- NA 

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


HTH, 
Eric
On Tue, Oct 30, 2018 at 10:13 PM Duncan Murdoch < [ mailto:murdoch.duncan at gmail.com | murdoch.duncan at gmail.com ] > wrote:

        
On 30/10/2018 3:56 PM, Sebastien Bihorel wrote:
I haven't looked up that quote, but it is likely describing a situation 
that isn't relevant to you. For you, the important part is that bar1 
and bar2 must be created within foo. They don't need to be returned 
from it. 

So my edit below of your code should do what you want. 

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

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

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

I get this output:
foo: x=0, y=0, z=0
bar1: x=1, y=1, z=1 
foo: x=1, y=1, z=1
bar2: x=2, y=2, z=2 
foo: x=2, y=2, z=2 

Duncan Murdoch 

______________________________________________ 
[ mailto:R-help at r-project.org | R-help at r-project.org ] mailing list -- To UNSUBSCRIBE and more, see 
[ https://stat.ethz.ch/mailman/listinfo/r-help | https://stat.ethz.ch/mailman/listinfo/r-help ] 
PLEASE do read the posting guide [ http://www.r-project.org/posting-guide.html | http://www.R-project.org/posting-guide.html ] 
and provide commented, minimal, self-contained, reproducible code.