statquant statquant - 3 months ago 17
R Question

Shortest lambda expression for monoadic function compositions in *apply

I tend to use

*apply
functions a lot and find it cumbersome when I used composed functions. I've seen
pipeR
and
magrittr
.
Say I want to do (I know it does not make sense)

lapply(-3:10, FUN=function(x){return(sum(abs(x)))})


What is the shortest way I can define
FUN=function(x){return(sum(abs(x)))}
, for now it seems that
{. %>% abs %>% sum}
is the shortest I found.

Is there a way to do
{ sum(abs(.)) }
or something similar?

Answer

Is this some kind of code golf challenge?

library(functional)
lapply(-3:10, Compose(abs, sum))

And of course, defining an operator is simple:

`%.%` <- function(x, y) Compose(y, x)
lapply(-3:10, sum %.% abs)

In fact, Hadley's pryr package defines this operator.