[R] environment and scoping

Charles C. Berry cberry at tajo.ucsd.edu
Sat Oct 4 19:52:59 CEST 2008





Rene,

What you have below does not make much sense. You have not provided a 
definition for fun.dat() nor have you given an example with which to run 
any of your functions.

The issue you raise about passing 'dat variable as a parameter as it can 
get pretty large' is not an issue.

Observe:

------------------
> x <- rnorm(1000000)
> gc()
           used (Mb) gc trigger (Mb) max used (Mb)
Ncells  136213  3.7     350000  9.4   350000  9.4
Vcells 1091921  8.4    1540913 11.8  1091931  8.4
> mean(x)
[1] -0.0004251693
> gc()
           used (Mb) gc trigger (Mb) max used (Mb)
Ncells  136405  3.7     350000  9.4   350000  9.4
Vcells 1091962  8.4    1697958 13.0  1092837  8.4
> object.size(x)
[1] 8000024
> mean(2*x)
[1] -0.0008503386
> gc()
           used (Mb) gc trigger (Mb) max used (Mb)
Ncells  136413  3.7     350000  9.4   350000  9.4
Vcells 1091962  8.4    2441693 18.7  2091968 16.0
-------------------

x occupies most of the Vcells in R's memory.

And the 'max used' does not increase when mean(x) is called - in other 
words, no copy of x is performed.

Only when another object is created ( '2*x' ) does 'max used' increase - 
almost doubling.

So, as long as you are not modifying 'dat' (in which case a local copy is 
made) , I think there is nothing to worry about.

HTH,

Chuck



On Sat, 4 Oct 2008, René Holst 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]]
>
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901


More information about the R-help mailing list