[R] Fwd: Evaluating a function within a pre-defined environment?
hadley wickham
h.wickham at gmail.com
Thu Dec 10 16:41:08 CET 2009
On Wed, Dec 9, 2009 at 4:48 PM, David Reiss <dreiss at systemsbiology.org> wrote:
> Ideally I would like to be able to use the function f (in my example)
> as-is, without having to designate the environment as an argument, or
> to otherwise have to use "e$x" in the function body.
e <- new.env()
e$x <- 3
f <- function(xx) x <<- x + xx
environment(f) <- e
f(1)
f(1)
f(2)
e$x
But I think you'd be better off doing it within the usual scoping rules:
new_adder <- function(init = 0) {
sum <- init
function(x) {
sum <<- sum + x
sum
}
}
f <- new_adder(3)
f(1)
f(2)
Hadley
--
http://had.co.nz/
More information about the R-help
mailing list