From murdoch.duncan at gmail.com  Mon Feb 23 22:54:05 2015
From: murdoch.duncan at gmail.com (Duncan Murdoch)
Date: Mon, 23 Feb 2015 16:54:05 -0500
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: <54EBA17D.7070802@gmail.com>

On 23/02/2015 3: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?
> 

Arguments aren't evaluated until they are used.  The force() function
can be used to force evaluation when you want it.

This is a feature:  it allows you to have arguments that are never
evaluated, because they are never used, or defaults that depend on
things that are calculated within the function.

Duncan Murdoch


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



[Rd] iterated lapply
Duncan Murdoch