Ali
Ali

Reputation: 9830

Fixing indents of a source and making it clean

Is there any suitable program to fix the indents of a R script already written?

For example if it is fed an script like this:

foo = function(x) {
a = 1
    print(a)
 }

It converts it to:

foo = function(x) {
    a = 1
    print(a)
}

Or better?

Upvotes: 3

Views: 272

Answers (2)

Dason
Dason

Reputation: 61913

In addition to Dirk's answer most decent editors allow you to correct the indentation of a script. For example in RStudio if you have the script open you can use Ctrl+i to update the indentation of whatever is selected.

Upvotes: 3

Dirk is no longer here
Dirk is no longer here

Reputation: 368201

Yes, use Yihui's formatR package.

Demo with before and after:

R> system("cat /tmp/fex.R")
foo = function(x) {
a = 1
    print(a)
 }
R>
R> library(formatR)
R> tidy.source("/tmp/fex.R",replace.assign=TRUE)
foo <- function(x) {
    a <- 1
    print(a)
} 
R> 

You can of course redirect to a new file using tidy.source(..., file="NewFile.R")

Upvotes: 11

Related Questions