[R] Appropriate method for sharing data across functions

Hadley Wickham hadley at rice.edu
Mon Apr 9 18:57:43 CEST 2012


> Make OPCON an environment and pass it into the functions that may read it or alter it.  There
> is no real need to pass it out, since environments are changed in-place (unlike lists).  E.g.,
>  > x <- list2env(list(one=1, two="ii", three=3))
>  > x
>  <environment: 0x0000000003110890>
>  > objects(x)
>  [1] "one"   "three" "two"
>  > x[["two"]]
>  [1] "ii"
>  > with(x, three+one)
>  [1] 4
>  > f <- function(z, env) { env[["newZ"]] <- z ; sqrt(z) }
>  > f(10, x)
>  [1] 3.162278
>  > x[["newZ"]] # put there by f()
>  [1] 10

The advantage of using a reference class is you get an object with
defined behaviour, and something that you can document more easily.

Hadley

-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-help mailing list