statquant statquant - 11 months ago 69
R Question

Shortest lambda expression for monoadic function compositions in *apply

I tend to use

functions a lot and find it cumbersome when I used composed functions. I've seen
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
, for now it seems that
{. %>% abs %>% sum}
is the shortest I found.

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

Answer Source

Is this some kind of code golf challenge?

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.