Skip to content
Prev 274717 / 398506 Next

Remote environments, calling functions

I don't think you said how you packaged this stuff up
and that is the critical part of your question.
Here is an example that does what I think you want to do.
It uses save() and load() for the serialization and I
serialize an environent full of data and functions.

In one session of R make some data and functions that use the
data in a fresh environment:

  env <- new.env()
  with(env, {
     r <- 0.5
     setRadius <- function(radius) r <<- radius
     area <- function() pi * r^2
  })

Serialize the environment env with

  save("env", file = tf <- tempfile(fileext=".rda"))
  # print(tf)
  # [1] "C:\\DOCUME~1\\wdunlap\\LOCALS~1\\Temp\\RtmpJNnRiu\\filef9f6711.rda"

In another session deserial that rda file with load and
use the environment env as you did in the first session:

  > load("C:\\DOCUME~1\\wdunlap\\LOCALS~1\\Temp\\RtmpJNnRiu\\filef9f6711.rda")
  > objects()
  [1] "env"
  > env$area()
  [1] 0.7853982
  > env$setRadius(10)
  > env$area()
  [1] 314.1593

If you serialize a function whose environment is not on the search list
then save serializes the environment of the function along with the function.
E.g., in the master session:

  > circleMaker <- function(r) {
  +     radius <- r
  +     function() pi * r^2
  + }
  > c1 <- circleMaker(10)
  > c2 <- circleMaker(200) # same function, different environment as c1
  > save("c1", "c2", file = tf <- tempfile(fileext=".rda"))
  > tf
  [1] "C:\\DOCUME~1\\wdunlap\\LOCALS~1\\Temp\\RtmpJNnRiu\\file2cc3696f.rda"

and in the slave session:

  > load("C:\\DOCUME~1\\wdunlap\\LOCALS~1\\Temp\\RtmpJNnRiu\\file2cc3696f.rda")
  > c1()
  [1] 314.1593
  > c2()
  [1] 125663.7
  > objects(environment(c2))
  [1] "r"      "radius"

If the function is in .GlobalEnv and then you need to add by hand the
names of the data in .GlobalEnv that it requires to run (or save all
of .GlobalEnv, probably under an alternate name).

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com