[R] Evaluation of defaults in functions

Duncan Murdoch murdoch at stats.uwo.ca
Fri Sep 29 16:50:51 CEST 2006


On 9/29/2006 10:12 AM, hadley wickham wrote:
>> > But doesn't R has a rather limited force of lazy evaluation? - you
>> > have no control over it, apart from that arguments are evaluated
>> > lazily.  This rather limited compared to other languages (no lazy
>> > lists etc)
>>
>> You do have more control than that.  You can't put a promise in a list,
>> but you can put one in an environment, e.g.
>>
>>  > x <- new.env()
>>  > y <- 1
>>  > delayedAssign("z", y, assign=x)
>>  > y <- 2
>>  > x$z
>> [1] 2
> 
> That's interesting.  Is it possible to treat an environment like a
> list in most situations?

There are some important differences:

Lists are regular R objects, which are copied when passed as args to 
functions.  Environments are passed by reference.

Lists have an ordering, and don't need names.  Environments only contain 
named things, and the order in which objects were put into them is not 
retained.

Lists do partial matching on named args, environments need full 
matching.  For example:

 > x <- list(abc=1)
 > x$a
[1] 1
 > y <- new.env()
 > y$abc <- 1
 > y$a
NULL
 > y$abc
[1] 1

Environments have enclosing environments, lists don't.  The $ operator 
doesn't search the enclosure, but get() does:

 > y$mean
NULL
 > get("mean", y)
function (x, ...)
UseMethod("mean")
<environment: namespace:base>

Set the parent of the environment to emptyenv() if you don't want this. 
  By default it's set to the current evaluation environment.

 > z <- new.env(parent=emptyenv())
 > get("mean", z)
Error in get(x, envir, mode, inherits) : variable "mean" was not found

Duncan Murdoch



More information about the R-help mailing list