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

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Mar 27 17:21:29 CEST 2017


On Mon, Mar 27, 2017 at 1:17 AM, Rolf Turner <r.turner at auckland.ac.nz> wrote:
>
> 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)

You can get the names of named arguments:

 > z = function(x,X){cos(x*X)}
 > names(formals(z))
 [1] "x" "X"


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

Another idea might be to use purrr:map instead, which is quite happy
with X in your function:

 >  xxx <- purrr::map(y,function(x,X){cos(x*X)},X=2*pi)
 > xxx
[[1]]
[1] 0.08419541

[[2]]
[1] 0.6346404

[[3]]
[1] 0.9800506

[[4]]
[1] 0.8686734

[[5]]
[1] -0.9220073

But don't feed `.x` to your purrrring cats, or fails silently:

 >  xxx <- purrr::map(y,function(x,.x){cos(x*.x)},.x=2*pi)
 > xxx
[[1]]
NULL

But who would have a function with `.x` as an argument?


> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list