From dtemplelang at ucdavis.edu  Mon Feb 23 22:52:29 2015
From: dtemplelang at ucdavis.edu (Duncan Temple Lang)
Date: Mon, 23 Feb 2015 13:52:29 -0800
Subject: [Rd] iterated lapply
In-Reply-To: <1424725069.2636.5.camel@physik.uni-freiburg.de>
References: <1424725069.2636.5.camel@physik.uni-freiburg.de>
Message-ID: <54EBA11D.1090601@ucdavis.edu>

Use force() (or anything that evaluates mycondition, e.g. your print):

function(mycondition) {
  force(mycondition)
  function(i) mycondition * i
}

within the lapply() loop. 

Not a bug, but does surprise people. It is lazy evaluation.

  D.

On 2/23/15 12:57 PM, Daniel Kaschek wrote:
> Hi everybody,
> 
> with the following code I generate a list of functions. Each function
> reflects a "condition". When I evaluate this list of functions by
> another lapply/sapply, I get an unexpected result: all values coincide.
> However, when I uncomment the print(), it works as expected. Is this a
> bug or a feature?
> 
> conditions <- 1:4
> test <- lapply(conditions, function(mycondition){
>   #print(mycondition)
>   myfn <- function(i) mycondition*i
>   return(myfn)
> })
> 
> sapply(test, function(myfn) myfn(2))
> 
> 
> 
> Cheers,
> Daniel
> 

-- 
Director, Data Sciences Initiative, UC Davis
Professor, Dept. of Statistics, UC Davis

http://datascience.ucdavis.edu
http://www.stat.ucdavis.edu/~duncan



[Rd] iterated lapply
Duncan Temple Lang