statquant - 10 months ago 63

R Question

I tend to use

`*apply`

`pipeR`

`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)))}`

`{. %>% abs %>% sum}`

Is there a way to do

`{ sum(abs(.)) }`

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.

Source (Stackoverflow)