From r.turner at auckland.ac.nz  Mon Mar 27 02:17:59 2017
From: r.turner at auckland.ac.nz (Rolf Turner)
Date: Mon, 27 Mar 2017 13:17:59 +1300
Subject: [Rd] A trap for young players with the lapply() function.
Message-ID: <b2f95986-2a82-e9d7-d5a2-32ffac793461@auckland.ac.nz>


 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.

Once one realises what is going on, it's all quite obvious, and usually
pretty easy to fix.  OTOH there are lots of functions around with second
or third arguments whose formal name is "X", and these can trip one up
until the penny drops.

This keeps happening to me, over and over again (with sufficiently long
intervals between occurrences so that my ageing memory forgets the 
previous occurrence).

Is there any way to trap/detect the use of an optional argument called 
"X" and thereby issue a more perspicuous error message?

This would be helpful to those users who, like myself, are bears of very 
little brain.

Failing that (it does look impossible) might it not be a good idea to 
add a warning to the help for lapply(), to the effect that if FUN has an 
optional argument named "X" then passing this argument via "..." will 
cause this argument to be taken as the first argument to lapply() and 
thereby induce an error?

cheers,

Rolf Turner

-- 
Technical Editor ANZJS
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276



[Rd] A trap for young players with the lapply() function.
Rolf Turner