[R] change function scope?

Gabor Grothendieck ggrothendieck at gmail.com
Fri May 27 01:42:22 CEST 2011


On Thu, May 26, 2011 at 5:09 PM, James McCreight <jlmccreight at gmail.com> wrote:
> I'm still getting used to R's scoping. I've run into the following situation
>
> value=0
> thefunction <- function() print( value )
> somefunction <- function() { value=99; thefunction() }
> somefunction()
>
> now, I understand that somefunction() returns 0 because thefunction() was
> defined with value=0 in its parent envrionment, it dosent look at all in the
> environment of somefunction. My question is can I re-scope thefunction in
> the somefunction environment?? (So that somefunction() returns 99). I've
> tried various uses of eval() and assign() with their keywords in the
> definition of somefunction and have had no luck at all.
>
> I do see that i could define thefunction in some external file and source it
> inside somefunction, but that seems clumsy.
>

Aside from explicitly setting the environment of thefunction, note
that this sort of thing is often an attempt to do OO programming
without realizing it.  With the proto package you could make this
explicit.  Here p is a proto object with property value and methods
thefunction and somefunction:

library(proto)
value <- 0
p <- proto(value = 99,
  thefunction = function(this) print(this$value),
  somefunction = function(this) this$thefunction()
)
p$somefunction() # 99

# we can also change the value property:

p$value <- 100
p$somefunction() # 100

# or create a child with its own value such that p delegates the two
methods to child but child overrides p's value with its own.

child <- p$proto(value = 3)
child$somefunction() # 3
p$somefunction() # still 100


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list