Links
Twitter
Search

Tuesday
Jan152013

Function Composition in R

I am learning to program in R with 40,000 other students by taking the excellent (and free!) Computing for Data Analysis course run by Coursera.

R has many useful functions for slicing and dicing data, particularly if you work in an industry built on CSV files. What is missing though are some of the function operators that I am used to using from my work with F#. This means I keep having to type brackets to terminate long expressions:

(a(b(c(d(2)))))

Fortunately functions are first class citizens in R and you can define infix operators. So the operators I am used to using in F# (>>, <<, |> and <|) are only a function definition away:

"%>>%" <- function(a,b) {
   function(x) {
     b(a(x))
   }
}

"%<<%" <- function(a,b) {
  function(x) {
    a(b(x))
  }
}

"%|>%" <- function(x,f) {
  f(x)
}

"%<|%" <- function(f,x) {
  f(x)
}

Now I can write function compositions without the hefty bracket tax:

(a %>>% b %>>% c %>>% d)(2)

and pipeline function applications too

2 %|>% function(x) { 2 * x } %|>% function(x) { 2 + x }

Now my R code can look a bit more like my F# code.

PrintView Printer Friendly Version