Question

Is there any tool (editor, script, whatever...) available that can automatically reformat R code? It does not need to be customizable but it must be able to recognize statements separated by either semicolons or newlines since this code has both. If it can put all statements on a separate line, consistently indent code blocks and consistently place braces I will be very happy.

Edit: summarizing findings

Thanks for the great answers. Here is what I've found.

  • Both ESS and StatET are great R editors and do a nice job of auto indenting blocks of code. StatET allows you to select-all and re-indent everything in a file at once. From what I could tell ESS allows you to indent an entire function def at once but not the entire file (please correct me if I missed it). Neither of these will fix brace placement or break up multi-statement lines. (Eg: i = n*b;a=i+1)
  • formatR is awesome. In addition to fixing indentation it will also place braces consistently and split up multi-statement lines.

Here's a little function I wrote so that I can convert an entire source dir (using the same underlying function as formatR which is strangely in the animation package).

library("animation")

tidy.all <- function(inDir = NULL, outDir = NULL, ...) {
    if (is.null(inDir) || is.na(outDir)) 
        stop("inDir can't be null or NA")
    if (!file.info(inDir)$isdir) 
        stop("inDir must be a directory")

    if (is.null(outDir) || is.na(outDir)) 
        stop("outDir can't be null or NA")
    if (!file.exists(outDir)) 
        dir.create(outDir)
    if (!file.info(outDir)$isdir) 
        stop("outDir must be a directory")

    for (f in dir(inDir)) {
        currFile <- file.path(inDir, f)
        if (length(grep(".*\\.R$", currFile, perl = T))) {
            outFile <- file.path(outDir, f)
            if (file.exists(outFile)) 
                stop(paste("refusing to overwrite", outFile))

            tidy.source(currFile, file = outFile, ...)
        }
    }
}
Was it helpful?

Solution

Although ESS is a much better long-term solution, if you just have a quick formatting job, perhaps this packge will help: http://yihui.name/en/?s=formatr.

OTHER TIPS

Emacs with ESS does it exceedingly well -- and the default settings as recommended by R Core are in Section 7 R coding standards of the R Internals manual.

I use StatET, and it works quite well for this.

You could also try the formatR package on CRAN.

Though I've never used it, perhaps the following eclipse plug-in http://www.walware.de/it/statet/ might be able to help.

You can use ctrl + I in statET to fix the indent of your code. However it is possible to use formatR package with code snippets that generate better result especially by assigning a hot key to it.

I had the same problem. There is a really EASY way for reformatting in R Studio : Just copy all your code and paste in a new R script

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top