Wednesday, 13 April 2005

Currying in R

I'm deep in the R language as I attempt to make sense of my data. Here's a nice trick I've learnt for when you want to customize one of R's panel plots.

Suppose you want to produce a set of plots for some of your variables. You fire up the pairs function:


and you get a nice set of 6 little plots showing AGE against LIBERALISM, AGE against EDUCATION, etc. etc. As it is hard to take all the information in, you decide to add a smoothing line in there:

pairs(~ AGE + LIBERALISM + EDUCATION, panel=panel.smooth)

But suppose you want to change the way panel.smooth operates. You could just pass in extra parameters, but that isn't always the case, and perhaps in any case you want to reuse the same parameters over again elsewhere - but without setting them globally via par.set().

We'll use a little computer science trick known as currying. Currying means creating a new function, based on the old one but with some arguments "pre-filled in".

First, make a copy of your target function:

mysmooth = panel.smooth

Now have a look at its arguments:


You should see a list of named parameters. There's one called col.smooth, which chooses the colour of the smoothing line. Let's edit it.

formals(mysmooth)$col.smooth = "turquoise"

And we'll change the plotting symbol to something smaller:

formals(mysmooth)$pch = "."

Now just pass this new function into pairs():

pairs(~ AGE + LIBERALISM + EDUCATION, panel=mysmooth)

and there you go. You can keep your mysmooth function around for whenever you want a particular "look and feel", but without remembering all the individual graphics parameters to set.