[R] Remote environments, calling functions
Peter Langfelder
peter.langfelder at gmail.com
Tue Oct 18 02:44:18 CEST 2011
On Mon, Oct 17, 2011 at 5:28 PM, Tyler Pirtle <rtp at google.com> wrote:
> Hi there,
>
> I'm trying to do something like a migration of an R program. I've got a
> function and some variables
> in an interactive-session:
>
> r <- .5
> ## estimatePi references r
> estimatePi <- function(seed) {
> set.seed(seed)
> numDraws <- 1e+05
> x <- runif(numDraws, min = -r, max = r)
> y <- runif(numDraws, min = -r, max = r)
> inCircle <- ifelse((x^2 + y^2)^0.5 < r, 1, 0)
> sum(inCircle)/length(inCircle) * 4
> }
>
> At some point later (in C) I package all this up and send it somewhere else,
> where deserialize it (with care):
>
>> ls(env)
> [1] "echoBack" "estimatePi" "r"
>> env$estimatePi
> function (seed)
> {
> set.seed(seed)
> numDraws <- 1e+05
> x <- runif(numDraws, min = -r, max = r)
> y <- runif(numDraws, min = -r, max = r)
> inCircle <- ifelse((x^2 + y^2)^0.5 < r, 1, 0)
> sum(inCircle)/length(inCircle) * 4
> }
>> env$r
> [1] 0.5
>
> Ok? So now i want to call estimatePi(10):
>
>> env$estimatePi(10)
> Error in runif(numDraws, min = -r, max = r) : object 'r' not found
>
> I've tried several different things and I'm stumped.
> My understanding of R function calls and environments is limited - but I'm
> not convinced that what I'm trying to do is
> completely out of reach. Any thoughts? ;)
Try do.call. Look at the help page and perhaps try
do.call(env$estimatePi, list(seed=10), envir = env)
My understanding is that when you call a function, it is executed in
the current environment (i.e., your "session" environment), not in
env. do.call allows you to specify the environment.
HTH
Peter
More information about the R-help
mailing list