Tuesday, December 28, 2010

Tools to tidy up R code

Last week we made an impassioned plea for attention to style in formatting R and SAS code.

While it's always better to adopt a consistent style and use it whenever you write code, the reality is that sometimes formatting slips (or you end up repurposing code that others wrote. In those situations, the formatR package (due to Yihui Xie) is a useful tool to help tidy up code.

Imagine that the poorly formatted and somewhat obfuscated code from the last entry has been copied to the clipboard:

plotdens=function(x,y,mytitle, mylab){densx = density(x)
densy = density(y);plot(densx,main=mytitle,lwd=3,xlab=mylab,
yvals,col="gray")};mytitle=paste("Test of ages: D=",round(fOo$statistic,3),
" p=",round(fOo$p.value,2),sep="");plotdens(age[female==1],
age[female==0],mytitle=mytitle,mylab="age (in years)")

Running the commands:


will generate the following output:

ds = read.csv("http://www.math.smith.edu/r/data/help.csv")
fOo = ks.test(age[female == 1], age[female == 0], data = ds)
plotdens = function(x, y, mytitle, mylab) {
densx = density(x)
densy = density(y)
plot(densx, main = mytitle, lwd = 3, xlab = mylab, bty = "l")
lines(densy, lty = 2, col = 2, lwd = 3)
xvals = c(densx$x, rev(densy$x))
yvals = c(densx$y, rev(densy$y))
polygon(xvals, yvals, col = "gray")
mytitle = paste("Test of ages: D=", round(fOo$statistic, 3), " p=",
round(fOo$p.value, 2), sep = "")
plotdens(age[female == 1], age[female == 0], mytitle = mytitle,
mylab = "age (in years)")

The cleaned up code is much easier to parse, with minimal effort. Some quibbles: I'm not as fond of using 4 spaces of indentation. And I always worry what'll happen if there are syntax errors (yipes!). But this is a useful tool to have in your box.


Ken said...

It uses the standard R parsing, so if there is a syntax error it nicely produces an error. As a consequence handling of comments is poor.

Kiran Joshi said...


There is an excellent editor which is available to code R. It allows auto indenting, simultaneous correction of a variables across a program file (or from a point onwards in a program) as well as color coding of the program code and has an inbuilt help function

It uses the Java IDE Eclipse as a platform but there is no need to know any java. It is byfar the best software in my knowledge to code R.
Its called StatET and can be downloaded off