[R] Assigning variables into an environment.

hadley wickham h.wickham at gmail.com
Thu Dec 10 05:29:19 CET 2009


On Wed, Dec 9, 2009 at 9:43 PM, Rolf Turner <r.turner at auckland.ac.nz> wrote:
>
> I am working with a somewhat complicated structure in which
> I need to deal with a function that takes ``basic'' arguments
> and also depends on a number of parameters which change depending
> on circumstances.
>
> I thought that a sexy way of dealing with this would be to assign
> the parameters as objects in the environment of the function in
> question.
>
> The following toy example gives a bit of the flavour of what I
> am trying to do:
>
> foo <- function(x,zeta) {
> for(nm in names(zeta)) assign(nm,zeta[nm],envir=environment(bar))
> bar(x)
> }
>
> bar <- function(x) {
> alpha + beta*exp(gamma*x)
> }
>
> v <- c(alpha=2,beta=3,gamma=-4)
>
> ls()
> [1] "bar" "foo" "v"
>
> foo(0.1,v)
>  alpha
> 4.01096
>
> 2+3*exp(-4*0.1)
> [1] 4.01096      # Check; yes it's working; but ...
>
> ls()
> [1] "alpha" "bar"   "beta"  "foo"   "gamma" "v"
>
> The parameters got assigned in the global environment (as well as in
> the environment of bar()? Or instead of?).
>
> I didn't want that to happen.
>
> Questions:
>
> (a) What did I do wrong?

The environment of bar is the environment in which it exists - the
global environment.

> (b) What am I not understanding about environments?

See above.

> (c) How can I get the parameters to be assigned in the environment of bar()
>    and ***NOT*** in the global environment?

Define foo inside bar and rely on the usual lexical scoping rules.

> (d) Is it time to go to the pub yet?

Yes.

Hadley


-- 
http://had.co.nz/




More information about the R-help mailing list