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

Rolf Turner r.turner at auckland.ac.nz
Mon Mar 27 02:17:59 CEST 2017


 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



More information about the R-devel mailing list