<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/r-best-practices-r-you-writing-the-r-way/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.quantinsti.com/blog/r-best-practices-r-you-writing-the-r-way/"> R programming</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img sizes="(max-width: 1200px) 100vw, 1200px" alt="" class="wp-image-8045" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Best-Practices-R-you-writing-the-R-way.jpg?w=450&ssl=1" data-recalc-dims="1"></p>
<p>By <a target="_blank" rel="nofollow" href="https://www.linkedin.com/in/milind-paradkar-b37292107/">Milind Paradkar</a></p>
<p>Any programmer inevitably writes tons of codes in his daily work. However, not all programmers inculcate the habit of writing clean codes which can be easily be understood by others. One of the reasons can be the lack of awareness among programmers of the best practices followed in writing a program. This is especially the case for novice programmers. In this post, we list some of the R programming best practices which will lead to improved code readability, consistency, and repeatability. Read on!</p>
<h3><strong>Best practices of writing in R</strong></h3>
<p><strong>1) Describe your code </strong>– When you start coding describe what the R code does in the very first line. For subsequent blocks of codes follow the same method of describing the blocks. This makes it easy for other people to understand and use the code.</p>
<p><strong>Example:</strong></p>
<pre># This code captures the 52-week high effect in stocks
# Code developed by Milind Paradkar</pre>
<p><strong>2) Load Packages</strong> – After describing your code in the first line, use the library function to list and load all the relevant packages needed to execute your code.</p>
<p><strong>Example:</strong></p>
<pre>library(quantmod);  library(zoo); library(xts);
library(PerformanceAnalytics); library(timeSeries); library(lubridate);</pre>
<p><strong>3) Use Updated Packages </strong>– While writing your code ensure that you are using the latest updated R packages. To check the version of any R package you can use the packageVersion function.</p>
<p><strong>Example:</strong></p>
<pre>packageVersion(&quot;TTR&quot;)
[1] ‘0.23.1’</pre>
<p><strong>4) Organize all source files in the same directory – </strong>Store all the necessary files that will be used/sourced in your code in the same directory. You can use the respective relative path to access them.</p>
<p><strong>Example:</strong></p>
<pre># Reading file using relative path
df = read.csv(file = &quot;NIFTY.csv&quot;, header = TRUE)

# Reading file using full path
df =  read.csv(file = &quot;C:/Users/Documents/NIFTY.csv&quot;, header = TRUE)</pre>
<p><strong>5) Use a consistent style for data structure types – </strong>R programming language allows for different data structures like vectors, factors, data frames, matrices, and lists. Use a similar naming for a particular type of data structure. This will make it easy to recognize the similar data structures used in the code and to spot the problems easily.</p>
<p><strong>Example:</strong><br>
You can name all different data frames used in your code by adding .df as the suffix.</p>
<pre>aapl.df   = as.data.frame(read.csv(file = &quot;AAPL.csv&quot;, header = TRUE))
amzn.df = as.data.frame(read.csv(file = &quot;AMZN.csv&quot;, header = TRUE))
csco.df  = as.data.frame(read.csv(file = &quot;CSCO.csv&quot;, header = TRUE))</pre>
<p><strong>6) Indent your code </strong>– Indentation makes your code easier to read, especially, if there are multiple nested statements like For-loop and If statement.</p>
<p><strong>Example:</strong></p>
<pre># Computing the Profit &amp; Loss (PL) and the Equity
dt$PL = numeric(nrow(dt))
for (i in 1:nrow(dt)){
   if (dt$Signal[i] == 1) {dt$PL[i+1] = dt$Close[i+1] - dt$Close[i]}
   if (dt$Signal[i] == -1){dt$PL[i+1] = dt$Close[i] - dt$Close[i+1]}
}</pre>
<p><strong>7) Remove temporary objects –</strong> For long codes, running in thousands of lines, it is a good practice to remove temporary objects after they have served their purpose in the code. This can ensure that R does not into memory issues.</p>
<p><strong>8) Time the code – </strong>You can time your code using the system.time function. You can also use the same function to find out the time taken by different blocks of code. The function returns the amount of time taken in seconds to evaluate the expression or a block of code. Timing codes will help to figure out any bottlenecks and help speed up your codes by making the necessary changes in the script.</p>
<p>To find the time taken for different blocks we wrapped them in curly braces within the call to the system.time function.</p>
<p>The two important metrics returned by the function include:<br>
i) User time – time charged to the CPU(s) for the code<br>
ii) Elapsed time – the amount of time elapsed to execute the code in entirety</p>
<p><strong> </strong><strong>Example:</strong></p>
<pre># Generating random numbers
system.time({
mean_1 = rnorm(1e+06, mean = 0, sd = 0.8)
})

user    system    elapsed
0.40      0.00       0.45</pre>
<p><strong>9) Use vectorization –</strong> Vectorization results in faster execution of codes, especially when we are dealing with large data sets. One can use statements like the ifelse statement or the with function for vectorization.</p>
<p><strong>Example:</strong><br>
Consider the NIFTY 1-year price series. Let us find the gap opening for each day using both the methods (using for-loop and with function) and time them using the system.time function. Note the time taken to execute the for-loop versus the time to execute the with function in combination with the lagpad function.</p>
<pre>library(quantmod)
# Using FOR Loop
system.time({
df = read.csv(&quot;NIFTY.csv&quot;)
df = df[,c(1,3:6)]
df$GapOpen = double(nrow(df))
for ( i in 2:nrow(df)) {
df$GapOpen[i] = round(Delt(df$CLOSE[i-1],df$OPEN[i])*100,2)
}
print(head(df))
})</pre>
<p><img sizes="(max-width: 666px) 100vw, 666px" alt="" class="wp-image-8054" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Best-Practices-Blog_Pic1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<pre># Using with function + lagpad, instead of FOR Loop
system.time({
df = read.csv(&quot;NIFTY.csv&quot;)
df = dt[,c(1,3:6)]

lagpad = function(x, k) {
c(rep(NA, k), x)[1 : length(x)]
}

df$PrevClose = lagpad(df$CLOSE, 1)
df$GapOpen_ = with(df, round(Delt(df$PrevClose,df$OPEN)*100,2))
print(head(df))
})</pre>
<p><img sizes="(max-width: 665px) 100vw, 665px" alt="" class="wp-image-8058" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Best-Practices-Blog_Pic2.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>10) Folding codes </strong>– Folding codes is a way wherein the R programmer can fold a code of line or code sections. This allows hiding blocks of code whenever required, and makes it easier to navigate through lengthy codes. Code folding can be done in two ways:<br>
i) Automatic folding of codes<br>
ii) User-defined folding of codes</p>
<p><strong>Automatic folding of codes: </strong>RStudio automatically provides the flexibility to fold the codes. When a coder writes a function or conditional blocks, RStudio automatically creates foldable codes.</p>
<p><strong>User-defined folding of codes: </strong><br>
One can also fold a random group of codes by using Edit -> Folding -> Collapse or by simply selecting the group of codes and pressing Alt+L key.</p>
<p><strong>User-defined folding can also be done via Code Sections:</strong><br>
To insert a new code section you can use the Code -> Insert Section command. Alternatively, any comment line which includes at least four trailing dashes (-), equal signs (=) or pound signs (#) automatically creates a code section.</p>
<p><img sizes="(max-width: 541px) 100vw, 541px" alt="" class="wp-image-8061" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Best-Practices-Blog_Pic3.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>11) Review and test your code rigorously – </strong>Once your code is ready, ensure that you test it code rigorously on different input parameters. Ensure that the logic used in statements like for-loop, if statement, ifelse statement is correct. It is a nice idea to get your code reviewed by your colleague to ensure that the work is of high quality.</p>
<p><strong>12) Don’t save your workspace</strong> <strong>–</strong> When you want to exit R it checks if you want to save your workspace. It is advisable to not save the workspace and start in a clean workspace for your next R session. Objects from the previous R sessions can lead to errors which can be hard to debug.</p>
<p><img sizes="(max-width: 437px) 100vw, 437px" alt="" class="wp-image-8063" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Best-Practices-Blog_Pic4.png?resize=437%2C135&ssl=1" data-recalc-dims="1"></p>
<p>These were some of the best practices of writing in R that one can follow to make your codes easy to read, debug and to ensure consistency.</p>
<h3><strong> </strong><strong>Next Step</strong></h3>
<p><strong> </strong>If you want to learn various aspects of <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/">Algorithmic trading</a> then check out the <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/epat/">Executive Programme in Algorithmic Trading (EPAT™)</a>. The course covers training modules like Statistics &amp; Econometrics, Financial Computing &amp; Technology, and Algorithmic &amp; Quantitative Trading. EPAT™ equips you with the required skill sets to be a successful trader. <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/epat/">Enroll now</a>!</p>
<p>The post <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/blog/r-best-practices-r-you-writing-the-r-way/">R Best Practices: R you writing the R way!</a> appeared first on <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/"></a>.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.quantinsti.com/blog/r-best-practices-r-you-writing-the-r-way/"> R programming</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 title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/1NRn4kh_7SA"></a></div>