<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/automated-email-reports-with-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://blog.journeyofanalytics.com/automated-email-reports-with-r/"> R programming – Journey of Analytics</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>R is an amazing tool to perform advanced statistical analysis and create stunning visualizations. However, data scientists and analytics practitioners do not work in silos, so these analysis have to be copied and emailed to senior managers and partners teams. Cut-copy-paste sounds great, but if it  is a daily or periodic task, it is more useful to automate the reports. So in this blogpost, we are going to learn how to do exactly that.</p>
<p>The R-code uses specific library packages to do this:</p>
<ul>
<li>RDCOMClient – to connect to Outlook and send emails. In most offices, Outlook is still the defacto email client, so this is fine. However, if you are using Slack or something different it may not work.</li>
<li>r2excel – To create an excel output file.</li>
</ul>
<p>The screenshot below shows the final email view:</p>
<div class="wp-caption"><img sizes="(max-width: 1119px) 100vw, 1119px" src="https://i1.wp.com/blog.journeyofanalytics.com/wp-content/uploads/2018/10/email-screenshot-1.jpg?w=450&ssl=1" alt="email screenshot" class="wp-image-338" data-recalc-dims="1">
<p class="wp-caption-text">email screenshot</p>
</div>
<p>As seen in the screenshot, the email contains the following:</p>
<ul>
<li>Custom subject with current date</li>
<li>Embedded image</li>
<li>Attachments – 1 Excel and 1 pdf report</li>
</ul>
<h2></h2>
<h2>Code Explanation:</h2>
<p>The code and supporting input files are available here, under the Projects page under Nov2018. The code has 4 parts:</p>
<ul>
<li>Prepare the work space.</li>
<li>Pull the data from source.</li>
<li>Cleaning and calculations</li>
<li>Create pdf.</li>
<li>Create Excel file.</li>
<li>Send email.</li>
</ul>
<p> </p>
<h2>Prepare the work space</h2>
<p>I always set the relative paths and working directories at the very beginning, so it is easier to change paths later. You can replace the link with a shared network drive path as well.</p>
<p>Load library packages and custom functions. My code uses the r2excel package which is not directly available as an R-cran package. So you need to install using devtools using the code below.</p>
<p>It is possible to do something similar using the “xlsx” package, but r2excel is easier.</p>
<pre>library(devtools)
install_github(&quot;kassambara/r2excel&quot;)
library(r2excel)</pre>
<p>Some other notes:</p>
<ul>
<li>you need the first 2 lines of code only for the first time you installation. From the second time onwards, you only need to load the library.</li>
<li>r2excel seems to work only with 64-bit installations of R and Rstudio.</li>
<li>you do need Java installed on your computer. If you see an error about java namespace, then check the path variables. There is a very useful thread on Stackoverflow, so take a look.</li>
<li>As always, if you see errors Google it and use the Stack Overflow conversations. In 99% of cases, you will find an answer.</li>
</ul>
<h2></h2>
<h2>Pull the data from source</h2>
<p>This is where we connect to an Excel CSV (or text) file. In practice, most people connect to a database of some kind. The R-script I am using connects to a .csv file, but I have added the code to a connect to a SQL database.</p>
<p>That code snippet is commented out, so feel free to substitute your own sql database links. The code will also work for Amazon EC2 cluster.</p>
<p>Some points to keep in mind:</p>
<ul>
<li>If you are using sqlquery() then please note that if your query has an error then R sadly shows only a standard error message. So test your query on SQL server to ensure that you are not missing anything.</li>
<li>Some queries do take a long time, if you are pulling from a huge dataset. Also the time taken will be longer in R compared to SQL server direct connection. Using the  Sys.time() command before and after the query is helpful to know how long the query took to complete.</li>
<li>If you are only planning to pull the data randomly, it may make sense to pull from SQL server and store locally. Use the fread() function to read those files.</li>
<li>If you are using R desktop instead of R-server, the amount of data you can pull may be limited to what your system configuration.</li>
<li>ALWAYS optimize your query. Even if you have unlimited memory and computation power, only pull the data you absolutely need. Otherwise you end up unnecessarily sorting through irrelevant data.</li>
</ul>
<h2></h2>
<h2>Cleaning and calculations</h2>
<p>For the current data, there are no NAs, so we don’t need to account for those. However, the read.csv() command creates factors, which I personally do not like, as they sometimes cause issues while merging.</p>
<p>Some of the column names have “.” where R converted the space in the names. So we will manually replace those with an underscore using the gsub() function.</p>
<p>We will also rank the apps based on categories of interest, namely:</p>
<ul>
<li>Most Popular Apps – by number of Reviews</li>
<li>Most Popular Apps – by number Downloads and Reviews</li>
<li>Most Popular Categories – Paid Apps only</li>
<li>Most popular apps with 1 billion installations.</li>
</ul>
<h2></h2>
<h2>Create pdf</h2>
<p>We are going to use the pdf() function to paste all graphs to a pdf document. Basically what this function does is write the graphs to a file rather than show on the console. So the only thing to remember is that if you are testing graphs or make an incorrect graph, everything will get posted to the pdf until you hit the “dev.off()” function. Sometimes if the graph throws an error you may end up with a blank page, or worse, with a corrupt file that cannot be opened.</p>
<p>Currently, the code I am only printing 2 simple graphs using ggplot() and barplot() functions, but you can include many other plots as well.</p>
<p> </p>
<h2>Create Excel file.</h2>
<p>The Excel is created in the sequence below:</p>
<ul>
<li>Specify the filename and create an object of type .xlsx This will create an empty Excel placeholder. It is only complete when you save the Workbook using the saveWorkbook() at the end of the section.</li>
<li>Use the sheets() to create different worksheets within the Excel.</li>
<li>The  xlsx.addHeader() adds a bold Header to each sheet which will help readers understand the content on the page. The r2excel package has other functions to add more informative text in smaller (non-header) font as well, if you need to give some context to readers. Obviously, this is optional if you don’t want to add them.</li>
<li>xlsx.addTable() – this is the crucial function that adds the content to Excel, the main “meat” of what you need to show.</li>
<li>saveWorkbook() – this function will save the Excel to the folder.</li>
<li>xlsx.openFile() – this function opens the file so you can view contents. I typically have the script running on automated mode, so when the Excel opens I am notified that the script completed.</li>
</ul>
<h2></h2>
<h2>Send email</h2>
<p>The email is sent using the following functions:</p>
<ul>
<li>OutApp() – creates an Outlook object. As I mentioned earlier, you do need Outlook and need to be signed in for this to work. I use Outlook for work and at home, so I have not explored options for Slack or other email clients.</li>
<li>outmail[[“To”]] – specify the people in the “to” field. You could also read email addresses from a file and pass the values here.</li>
<li>outmail[[“cc’]] – similar concept, for the cc field.</li>
<li>outmail[[“Subject”]] – I have used the paste0() function to add the current date to the subject, so recipients know it is the latest report.</li>
<li>outMail[[“HTMLBody”]] – I used the HTML body so that I can embed the image. If you don’t know HTML programming, no worries! The code is pretty intuitive, you should be able to follow what I’ve done. The image basically is an attachment which the HTML code is forcing to be viewed within the body of the email. If you are sending the email to people outside the organization, they may see a small box instead of the image with a cross on the top left (or right) of the box. Usually, when you hover your mouse near box and right click, it will ask them to download images. You may have seen similar messages in gmail, along with a link to “show images” or ‘always show images from this sender’. You obviously cannot control what the recipient selects, but testing by sending to yourself first helps smoothing out potential aesthetic issues.</li>
<li>outMail[[“Attachments”]] – function to add attachments.</li>
<li>outMail$Send() – until you run this command, the mail will not be send. If you are using this in office, you may get a popup asking you to do one of the following. Most  of these will generally go away after the first use, but if they don’t, please look up the issue on StackOverflow or contact your IT support for firewall and other security settings.
<ul>
<li>popup to hit “send”</li>
<li>popup asking you to “classify” the attachments (internal / public/ confidential) Select as appropriate. For me, this selection is usually  “internal”</li>
<li>popup asking you to accept “trust” settings</li>
<li>popup blocker notifying you to allow backend app to access Outlook.</li>
</ul>
</li>
</ul>
<p> </p>
<p>That is it – and you are done! You have successfully learned how to send an automated email via R.</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://blog.journeyofanalytics.com/automated-email-reports-with-r/"> R programming – Journey of Analytics</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/nZVjzlXgjQE" height="1"></a></div>