16
votes

Is there something like a function composition in R?

I think in haskell it's somthing like "(.)" and in agda it's the ring operator.

Also, I find litte information on high level functional programming in R. I found the Functions "Reduce", "Map", "Filter"..., are there more? Any pointers?

3
To get some really useful pointers on functional programming, have a look at this answer to a previous question: stackoverflow.com/questions/4874867/… - Andrie

3 Answers

19
votes

The functional package has a Compose functional which generalizes to any number of functions:

set.seed(123)
x <- matrix(runif(100), 10, 10)
mean(rowSums(scale(x)))
# [1] 5.486063e-18

library(functional)
Compose(scale, rowSums, mean)(x)
# [1] 5.486063e-18

(Note that the functions are applied from left to right.)

10
votes

You may make compositing function like this:

composite<-function(f,g) function(...) f(g(...))

f<-function(x) x+1;
g<-function(x) x*2;
composite(f,g)(7)
composite(g,f)(7)

or make operator of this.

About the second point, there are lots of such; I think the most used are the *apply family (sapply, mapply, tapply, lapply, apply...).

1
votes

There is now a compose function in the purrr library. By default composition is made from right to left, as in Haskell, but it can be reversed with the .dir param:

library(purrr)
f = function(x) x+1
g = function(x) x*3

> compose(g,f)(1)
[1] 6
> compose(f,g, .dir="forward")(1)
[1] 6