Are you the type of person that likes your code to be identically indented? for spacing to be consistent throughout your script, everything to be clear and aligned, read easily and just look nice? Well, I am. Often I get tremendously untidy code from other coders (those bandits), and it takes me way too much time to understand where this for loop starts, where that function ends etc. Reading this code gets especially confusing if the person for example uses nested for loops (for loop inception - a for in a for in a for…). Well I came across a package in R that eliminated this problem all together, called
formatR - see https://cran.r-project.org/web/packages/formatR/index.html. To illustrate how this package works, I use a section of code from Prof Hedibert Freitas Lopes, found here: http://hedibert.org/wp-content/uploads/2014/06/Application2-stochasticvolatility-R.txt. Now if you’ve ever seen the code Prof Lopes (gratuitously) posts, you’ll know it’s very neat. So to illustrate how the
formatR works, I mess it up a bit, playing with the spaces and the indentation. Below is the resulting code.
As you can see, while it’s easy to spot out a function here and there and a for loop, it’s really difficult to quickly read and see where a bracket begins and where it ends. Now to solve this, we firstly load the
formatR package and then get ready to use the function
tidy_source(). To obtain the cleaned code, we simply copy the section of code we’d like to format, and then merely run the
tidy_source() function, adapting the parameters as we choose. Some of these parameters include
width_cutoff which determines when a link-break is inserted,
blank which determines whether or not to purge comments and blank lines and arrow, which if set to true, replaces all = with <-.
tidy_source then spits out the cleaned, formatted code in the console, ready for you to copy into you new cleaned and formatted script, as you can see below. Pretty cool hey?
formatR package also contains some other functions like
tidy_dir(), which formats all of the the scripts in a directory. In this case, it doesn’t spit the code out in the console, instead overwriting the original R scripts with the cleaned data.
My favorite function however has to be
tidy_app. This function when run, opens up a Shiny app which allows you to format your code. Here you simply paste your code in the window, choose you format settings on the left, press Tidy my Code and voila, your cleaned and formatted code appears in the window, ready to copy and use.
While this is nothing groundbreaking (Although personally, I find the Shiny app pretty cool), I still believe it to be a really useful package which should help keep all of your code consistent in appearance, thereby making it easier for your peers/colleagues to understand, and vice-versa.