[R] How to move an internal function to external keeping same environment?

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 15 17:07:27 CET 2010


On Mon, Nov 15, 2010 at 10:49 AM, Matthieu Stigler
<matthieu.stigler at gmail.com> wrote:
> I have limited understanding of Duncan's points but will follow your advice
> not to do it like this. If I am nervertheless quit keen to use foo2
> externally, is the use of either assign() in foo1, or mget() in foo2 more
> indicated? Or are the same kind of remarks raised against environment() also
> relevant for assign() and mget()?
>

Another way to approach this, which is safer, is to put it into an OO
framework creating a proto object (package proto) that contains the
shared data and make foo and foo2 its methods.

library(proto) # see http://r-proto.googlecode.com

# create proto object

p <- proto()

# add foo method which stores mydata in receiver object
# and runs foo2

p$foo <- function(.) { .$mydata <- 1:3; .$foo2() }

# add foo2 method which grabs mydata from receiver
# and calculates result

p$foo2 <- function(.) sum(.$mydata)

# run foo method - result is 6

p$foo()


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