From ccberry at ucsd.edu  Tue Mar 28 04:26:55 2017
From: ccberry at ucsd.edu (Charles C. Berry)
Date: Mon, 27 Mar 2017 19:26:55 -0700
Subject: [Rd] A trap for young players with the lapply() function.
In-Reply-To: <b2f95986-2a82-e9d7-d5a2-32ffac793461@auckland.ac.nz>
References: <b2f95986-2a82-e9d7-d5a2-32ffac793461@auckland.ac.nz>
Message-ID: <alpine.OSX.2.20.1703271912020.6811@charles-berrys-macbook.local>

On Mon, 27 Mar 2017, Rolf Turner wrote:

>
> From time to time I get myself into a state of bewilderment when using
> apply() by calling it with FUN equal to a function which has an "optional" 
> argument named "X".
>
> E.g.
>
>    xxx <- lapply(y,function(x,X){cos(x*X)},X=2*pi)
>
> which produces the error message
>
>> Error in get(as.character(FUN), mode = "function", envir = envir) :
>>   object 'y' of mode 'function' was not found
>
> This of course happens because the name of the first argument of lapply() is 
> "X" and so it takes the value of this first argument to be the supplied X 
> (2*pi in the foregoing example) and then expects what the user has denoted by 
> "y" to be the value of FUN, and (obviously!) it isn't.
>

The lapply help page addresses this issue in `Details' :

"it is good practice to name the first two arguments X and FUN if ... is 
passed through: this both avoids partial matching to FUN and ensures that 
a sensible error message is given if arguments named X or FUN are passed 
through ..."

So that advice suggests something like:

xxx <- lapply( X=y, FUN=function(X,x){cos(X*x)}, x=2*pi )

Best,

Chuck



[Rd] A trap for young players with the lapply() function.
Charles C. Berry