Re: [R] Evaluation of defaults in functions

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Thu 28 Sep 2006 - 21:42:04 GMT

"Gabor Grothendieck" <ggrothendieck@gmail.com> writes:

> foo2 could be written:
>
> foo3 <- function(x, y = x) { force(y); x <- 0; y }
>
> to make it clear that evaluation of y is being forced. See ?force

And, to answer the specific question: Yes, R has lazy evaluation, everywhere. Arguments are always evaluated if and when they are needed.  

> On 9/28/06, Ulrich Keller <uhkeller@web.de> wrote:
> > Hello,
> >
> > and sorry if this is already explained somewhere. I couldn't find anything.
> >
> > R (2.3.1, Windows) seems to perform some kind of lazy evaluation when
> > evaluating defaults in function calls that, at least for me, leads to
> > unexpected results. Consider the following, seemingly equivalent functions:
> >
> > > foo1 <- function(x, y=x) {
> > + x <- 0
> > + y
> > + }
> > > foo1(1)
> > [1] 0
> > > foo2 <- function(x, y=x) {
> > + y <- y
> > + x <- 0
> > + y
> > + }
> > > foo2(1)
> > [1] 1
> >
> > Obviously, y is not evaluated until it is used in some way. I would
> > expect it to be evaluated where it is defined. Is this intended behavior?
> > Thanks for clarifying,
> >
> > Uli
> >
> > ______________________________________________
> > R-help@stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
   O__  ---- Peter Dalgaard             ุster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Fri Sep 29 08:18:03 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 29 Sep 2006 - 03:30:13 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.