[Rd] suggestion: "." in [lsv]apply()

Sokol Serguei @oko| @end|ng |rom |n@@-tou|ou@e@|r
Thu Apr 16 16:24:54 CEST 2020


I would like to make a suggestion for a small syntactic modification of 
FUN argument in the family of functions [lsv]apply(). The idea is to 
allow one-liner expressions without typing "function(item) {...}" to 
surround them. The argument to the anonymous function is simply referred 
as ".". Let take an example. With this new feature, the following call

sapply(split(mtcars, mtcars$cyl), function(d) summary(lm(mpg ~ wt, 
#        4         6         8
#0.5086326 0.4645102 0.4229655

could be rewritten as

sapply(split(mtcars, mtcars$cyl), summary(lm(mpg ~ wt, .))$r.squared)

"Not a big saving in typing" you can say but multiplied by the number of 
[lsv]apply usage and a neater look, I think, the idea merits to be 
To illustrate a possible implementation, I propose a wrapper example for 

wsapply=function(l, fun, ...) {
     if (is.name(s) || is.call(s) && s[[1]]==as.name("function")) {
         sapply(l, fun, ...) # legacy call
     } else {
         sapply(l, function(d) eval(s, list(.=d)), ...)

Now, we can do:

wsapply(split(mtcars, mtcars$cyl), summary(lm(mpg ~ wt, .))$r.squared)

or, traditional way:

wsapply(split(mtcars, mtcars$cyl), function(d) summary(lm(mpg ~ wt, 

the both work.

How do you feel about that?


More information about the R-devel mailing list