[R] lazy evaluation question

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Jan 19 18:40:44 CET 2009


Gabor Grothendieck wrote:
> Note that
> 
> rm(i)
> for(j in 1:4) F(j)
> 
> raises an error due to scoping issues.

Yes. This has nothing to do with lazy evaluation, and everything to do 
with scoping: f is not defined in the scope of F, so does not know about 
its variables (nor those in the implicit loop of lapply()).

Notice also that in

lapply(1:4,function(i) F(i))

it would be pretty weird if lapply would behave differently depending on 
the name of formal arguments of the function, i.e. if

lapply(1:4,function(meep) F(meep))

gave a different result. And f() depends on looking for a variable i 
outside of the function.

> On Sun, Jan 18, 2009 at 10:02 PM,  <markleeds at verizon.net> wrote:
>> I've been going back to old difficult R-list "evaluation" emails that I save
>>  in order to understand evaluation better and below still confuses me. Could
>> someone explain why A) works and B) doesn't. A variant of below is in the
>>  Pat's Inferno book also but I'm still not clear on what is happening.
>> Thanks.
>>
>> f <- function() {
>>  # FORCING i here doesn't help
>>  i*i
>> }
>>
>> F <- function(i) {
>>  force(i)
>>  print(f())
>>  }
>>
>> A) THIS WORKS
>> for ( i in 1:4 ) {
>>  F(i)
>> }
>>
>> B) THIS DOESN'T
>> lapply(1:4,function(i) F(i))


-- 
    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 at biostat.ku.dk)              FAX: (+45) 35327907




More information about the R-help mailing list