[R] Assigning variables into an environment.

Duncan Murdoch murdoch at stats.uwo.ca
Thu Dec 10 11:26:53 CET 2009


On 09/12/2009 11:29 PM, hadley wickham wrote:
> 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.

Not quite:  it is by default the environment in which it was created. 
However, it can be copied somewhere else, or have its environment 
changed (more accurately, have a copy made with a new environment 
attached, as Gabor did), so it's not always the one in which it exists.

Rolf asked for articles about environments.  I don't know of any, but 
they are discussed in the R Language Definition.  The discussion is 
spread out, but I think it is reasonably well indexed.  Most of what 
Rolf needs is in the earlier entries in the manual.

Duncan

>> (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
> 
>




More information about the R-help mailing list