[R] environment and scoping

Gabor Grothendieck ggrothendieck at gmail.com
Sat Oct 4 19:55:04 CEST 2008


Please provide complete examples that include test drivers.
Here is main.fun reworked to eliminate the error in the arg
list and also changing the environment of aux.fun:

main.fun <- function(aux.fun, dat) {
   x <- 1
   environment(aux.fun) <- environment()
   aux.fun()
}

aux.fun.one <- function() mean(dat) + x
aux.fun.two <- function() mean(dat) - x

main.fun(aux.fun.one, 1:10)
main.fun(aux.fun.two, 1:10)


This can also be done with the proto package:

P is a proto object used as a Trait in the sense of the proto vignette.
(A Trait plays the role of a class but its actually an object just like
all other proto objects and is not a separate construct.)  P has the
fun method as its only component.

p1 and p2 are children of P.  They each have dat and aux.fun
as components.

P delegates fun to each of p1 and p2 and when p1$fun() and p2$fun()
run they also create an x component in p1 and p2.

library(proto)
P <- proto(fun = function(this) { this$x <- 1; this$aux.fun()})

p1 <- P$proto(dat = 1:10, aux.fun = function(this) with(this, mean(dat) + x))
p1$fun()

p2 <- P$proto(dat = 1:10, aux.fun = function(this) with(this, mean(dat) - x))
p2$fun()

# look at p1 and p2
p1$as.list()
p2$as.list()


# If children p1 and p2 are never themselves parents then additional
simplification is
# possible.

p1 <- P$proto(dat = 1:10, aux.fun = function(this) mean(dat) + x)
p1$fun()

p2 <- P$proto(dat = 1:10, aux.fun = function(this) mean(dat) - x)
p2$fun()


On Sat, Oct 4, 2008 at 12:50 PM, René Holst <rho at aqua.dtu.dk> wrote:
> I haven't quite figured out how I can change the environment of a function.
> I have a main function and want to use different auxillary functions, which I supply as parameter (or names). What I want to do is something like this:
>
> main.fun=function(aux.fun,dat){
>  x <- 1
>  fun.dat()
> }
>
> aux.fun.one=function(){
>  mean(dat)+x
> }
>
> aux.fun.one=function(){
>  median(dat)-x
> }
>
> I don't want to transfer the dat variable as a parameter as it can get pretty large. The enclosing environment of both auxillary functions is the Global environ, so they cannot see neither dat nor x as they exist inside the scope of the main function. So how do I do this?
>
> Thanks,
>
> René
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



More information about the R-help mailing list