<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/r-code-best-practices/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.thertrader.com/2018/09/01/r-code-best-practices/"> R – The R Trader</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Nothing is more frustrating than a long piece of code with no standard way of naming elements, presenting code or organizing files. It’s not only unreadable but more importantly not reusable. Unfortunately, unlike other programming languages, R has no widely accepted coding best practices. Instead there has been various attempts to put together a few sets of rules. This post is trying to fill the gap by summarizing and/or extracting what I foundÂ relevant in those various attempts. It also includes some tips I came up with after years of using R on a daily basis.</p>
<h4><strong>1 – Naming conventions</strong></h4>
<p>R has no naming conventions that are generally agreed upon. As a newcomer to R it's useful to decide which naming convention to adopt.</p>
<ul>
<li>There are 5 naming conventions to choose from:
<ul>
<li><span contenteditable="true"><span><em>alllowercase</em></span>: e.g. adjustcolor</span></li>
<li><span contenteditable="true"><span><em>period.separated</em></span>: e.g. plot.new</span></li>
<li contenteditable="true"><span contenteditable="true"><span><em>underscore_separated</em></span>: e.g. numeric_version</span></li>
<li contenteditable="true"><span contenteditable="true"><span><em>lowerCamelCase</em></span>: e.g. addTaskCallback</span></li>
<li contenteditable="true"><span contenteditable="true"><span><em>UpperCamelCase</em></span>: e.g. SignatureMethod</span></li>
</ul>
</li>
<li><span contenteditable="true">Strive for names that are concise and meaningful</span></li>
<li><span contenteditable="true">Generally, variable names should be nouns and function names should be verbs.</span></li>
<li><span contenteditable="true">Strive for names that are concise and meaningful</span></li>
<li>Generally, variable names should be nouns and function names should be verbs.</li>
<li>Not exported and helper functions always start with “.”</li>
<li>Local variables and functions are all in small letters and in “.” syntax (do.something, get.xyyy). It makes it easy to distinguish local vs global and therefore leads to a cleaner code.</li>
<li>File names should be meaningful and end in .R.</li>
<li>Pick one naming convention and stick to it. My suggestion:
<ul>
<li><span contenteditable="true"><span><strong>Files</strong></span>: underscore_separated, all lower case: e.g. numeric_version</span></li>
<li><span contenteditable="true"><span><strong>Functions</strong></span>: period.separated, all lower case: e.g. my.function</span></li>
<li><span contenteditable="true"><span><strong>Variables</strong></span><span>: lowerCamelCase: e.g. addTaskCall</span></span></li>
</ul>
</li>
</ul>
<h4><strong><span>2 – Files organisation</span></strong></h4>
<p><span contenteditable="true"><span>They way files are organised helps making the code more readable. Similarly, the way the code is organised within a file has a significant impact on readability. Files might also have specific purposes. Some might contain only functions that will be used by other files, some might be used to update packages etc…</span></span></p>
<h5><span contenteditable="true"><span><strong>2.1 – How to organise the files within a project?</strong></span></span></h5>
<ul>
<li><span contenteditable="true">Use the project facility of RStudio each time you start working on a new project</span></li>
<li>Keep all of the source files for a project in one directory and use relative paths to access them</li>
<li>Separate files that contain functions that will be used by other parts of the code from the core of the code</li>
<li>Consider what working directory you are in when sourcing a script.</li>
</ul>
<h5><span contenteditable="true"><span><strong>2.2 –Â How to organise the code within each file?</strong></span></span></h5>
<ul>
<li><span contenteditable="true"><span>Start each file with a comment saying who wrote it and when, what it contains, and how it fits into the larger program.</span></span></li>
<li>Then load all required packages.</li>
<li>Then source required files if any</li>
<li>Then your code starts</li>
<li>Break code up into separate files (generally &lt;2000 - 3000 lines).</li>
</ul>
<pre>
#############################################################
## Stuff I have to do
## thertrader@gmail.com - Feb 2018
#############################################################
â€‹
##############################
# 0 - Load librairies
##############################
library(zoo)
library(xts)

â€‹############################## 
# 1 - Source file 
##############################
dataPath &amp;amp;amp;lt;- &quot;C:/some_directory/some_sub_directory/&quot; 
dataFile &amp;amp;amp;lt;- &quot;some_functions.R&quot; 
source(paste0(dataPath,dataFile))

##############################
# 2 - Start my code
##############################
myPlot &amp;amp;amp;lt;- plot(data,type=&quot;l&quot;)
</pre>
<h5><span contenteditable="true"><span><strong>2.3 –Â Files of functions</strong></span></span></h5>
<ul>
<li contenteditable="true"><span contenteditable="true"><span>Write functions (and even a package) to automate things. Packages require a lot of discipline, documentation, and structure, which really help to enforce best practices</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>A file of functions must include related functions.</span></span></li>
<li contenteditable="true"><span contenteditable="true">Put function definitions at the top of your file (if not too many). Function names can also be retrieved directly within RStudio.</span></li>
<li contenteditable="true"><span contenteditable="true">Each function should have a single, focused task</span></li>
<li contenteditable="true"><span contenteditable="true"><span>If a function starts to get really complicated, consider separating parts out as separate functions. (Think reuse)</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Precede each function with a comment regarding its task and the format of the input and output.</span></span></li>
</ul>
<pre>
#############################################################
## Date Functions 
##
## dd.mm.yyyy.to.date: 22.10.2004 to a date
## yyyy-mm-dd.to.date: 2008-07-22 to a date
## dd-mm-yyyy.to.date: 12-05-2001 to a date
##
## thertrader@gmail.com - Jan 2008... 
############################################################

## 22.10.2004 to a date
dd.mm.yyyy.to.date &amp;amp;amp;lt;- function(theDate) {
 myDate &amp;amp;amp;lt;- as.Date(theDate, format = &quot;%d.%m.%Y&quot;)
 return(myDate)
}

## 2008-07-22 to a date
yyyy-mm-dd.to.date &amp;amp;amp;lt;- function(theDate) {
 myDate &amp;amp;amp;lt;- as.Date(theDate, format = &quot;%Y-%m-%d&quot;)
 return(myDate)
}

## 12-05-2001 to a date
dd-mm-yyyy.to.date &amp;amp;amp;lt;- function(theDate) {
 myDate &amp;amp;amp;lt;- as.Date(theDate, format = &quot;%m-%d-%Y&quot;)
 return(myDate)
}
</pre>
<h5><span contenteditable="true"><span><strong>2.4 –Â Files with packages and addins</strong></span></span></h5>
<ul>
<li>R and packages can be updated with the installr command on a (Windows) computer that already has R installed but when installing R on a brand new computer or a new operating system another method is needed</li>
<li>For installation on a brand new computer or a new operating system, It’s very handy to keep a file with all packages and addins that you need and install them right after R has been installed for the first time. Below is a template file</li>
</ul>
<pre>
##################################################
## Install Package Automatically - to run after R has been upgraded/installed
##
## thertrader@gmail.com - Aug 2010...
##################################################

install.packages(c(
&quot;data.table&quot;,
&quot;DEoptim&quot;,
&quot;devtools&quot;,
&quot;dplyr&quot;,
&quot;DT&quot;,
&quot;dygraphs&quot;,
&quot;ggplot2&quot;,
&quot;xts&quot;,
&quot;PerformanceAnalytics&quot;))

install.packages(&quot;taskscheduleR&quot;, repos = &quot;http://www.datatailor.be/rcube&quot;, type = &quot;source&quot;)

</pre>
<h4>3 – Syntax</h4>
<ul>
<li contenteditable="true">Place spaces around all infix operators (=, +, -, &lt;-, etc.).</li>
<li contenteditable="true"><span contenteditable="true"><span>Use &lt;-, not =, for assignment.</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Use comments to mark off sections of code.</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Comment your code with care. Comments should explain the why, not the what</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Each line of a comment should begin with the comment symbol and a single space</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>An opening curly brace should never go on its own line and should always be followed by a new line; a closing curly brace should always go on its own line, unless followed by else.</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Always indent the code inside the curly braces.</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Keep your lines less than 80 characters.This is the amount that will fit comfortably on a printed page at a reasonable size. If you find you are running out of room, this is probably an indication that you should encapsulate some of the work in a separate function.</span></span></li>
</ul>
<h4><strong>4 – Miscellaneous</strong></h4>
<ul>
<li contenteditable="true"><span contenteditable="true"><span>Use RStudio</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Use version control when you start sharing code. RStudio ships with integrated facilities to access GitHub and SVN</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Keep track of versions (of data, of functions).</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Always start with a clean environment instead of saving the workspace.</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Keep track of session information in your project folder.</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Keep track of the memory used by your program.</span></span></li>
<li contenteditable="true"><span contenteditable="true"><span>Have someone else review your code: hence this document <img alt="ðŸ˜‰" src="https://i2.wp.com/s.w.org/images/core/emoji/11/72x72/1f609.png?w=456&ssl=1" class="wp-smiley" data-recalc-dims="1"></span></span></li>
</ul>
<p><span contenteditable="true"><span>This post has been written using my own experience and the following documents:</span></span></p>
<ul>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="http://stat405.had.co.nz/r-style.html" target="_blank">R Style Guide</a></span></span></li>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="https://csgillespie.github.io/efficientR/" target="_blank">Efficient R Programming</a></span></span></li>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="https://stackoverflow.com/questions/2258092/what-best-practices-do-you-use-for-programming-in-r" target="_blank">What best practices do you use for programming in R? (StackOverflow)</a></span></span></li>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="https://journal.r-project.org/archive/2012-2/RJournal_2012-2_Baaaath.pdf" target="_blank">The State of Naming Conventions in R</a></span></span></li>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="https://swcarpentry.github.io/r-novice-inflammation/06-best-practices-R/" target="_blank">Best Practices for writing R</a></span></span></li>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="http://adv-r.had.co.nz/Style.html" target="_blank">Advanced R: Style Guide</a></span></span></li>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="https://www.r-bloggers.com/consistent-naming-conventions-in-r/" target="_blank">Consistent Naming Conventions in R</a></span></span></li>
<li contenteditable="true"><span contenteditable="true"><span><a rel="nofollow" href="https://google.github.io/styleguide/Rguide.xml" target="_blank"><span>Google’s R Style Guide</span></a></span></span></li>
</ul>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.thertrader.com/2018/09/01/r-code-best-practices/"> R – The R Trader</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/PF3VrQEZX08" height="1"></a></div>