<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-markdown-for-documents-with-logos-watermarks-and-corporate-styles-by-ellis2013nz/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://ellisp.github.io/blog/2017/09/09/rmarkdown"> Peter's stats stuff - R</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>R Markdown in corporate settings</h2>
<p>I’ve been busy recently writing a paper at work using <a rel="nofollow" href="http://rmarkdown.rstudio.com/" target="_blank">R Markdown</a>, the wonderful tool provided by the folks at RStudio “to weave together narrative text and code to produce elegantly formatted output”. I don’t use R Markdown for my blog, because I prefer to separate my analytical scripts from the text and reintegrate the products by hand (I have my reasons, not necessarily good ones, but reasons of a sort). But in many contexts the integration of the code, output and text in R Markdown is a fantastic way to quickly and easily produce good-looking content.</p>
<p>In most organisations I’ve worked for, documents need to reflect the corporate look and feel. Typically, details are defined in a style guide and manifested in Microsoft Word and PowerPoint templates. Important details include permissible fonts, heading styles, design elements’ colours, and so on. In an organisation which does a lot of statistical graphics, you might also have guidelines for colours and other thematic aspects of plots.</p>
<p>I found myself having to solve a few minor problems to get my R Markdown at work generating a stand-alone HTML file that looks close enough to the look and feel that customers wouldn’t get a jolt when they saw the result and ask me to re-do it in Word. So today’s blog post jots down some of what I learned, if only so I’ve got it all in one place for myself.</p>
<p>To illustrate this, I set up a GitHub repository of <a rel="nofollow" href="https://github.com/ellisp/rmarkdown-corporate-eg" target="_blank">source code for a hypothetical project</a> involving some data management, analysis and report writing. Feel free to clone and re-use it (attribution would be nice). Here’s a screenshot of the top of my hypothetical report:</p>
<p><a rel="nofollow" href="http://ellisp.github.io/presentations/rmarkdown-styled-demo.html" target="_blank"><img src="https://i0.wp.com/ellisp.github.io/img/0109-rmarkdown-screenshot.png?w=100%25" data-recalc-dims="1"></a></p>
<p>Clicking on the image will get you the whole report including some plots of New Zealand’s regional tourism, which I used as readily-available data.</p>
<h2>Structuring the project</h2>
<p>I divide most of my projects of this sort into four conceptual tasks:</p>
<ul>
<li><em>setup</em> – loading up packages and defining functions and assets that will be used repeatedly</li>
<li><em>data munging</em> – download / extraction / creation and management into a stable state to be referred to throughout the project</li>
<li><em>analysis</em></li>
<li><em>building outputs</em> such as reports, presentations and web tools</li>
</ul>
<p>These tasks aren’t done in a simple linear manner. For example, sometimes I start writing parts of the report first. Nearly always I don’t know what “functions and assets will be used repeatedly” until I find myself doing similar things a few times.</p>
<p>This project is set up as a folder system comprising a single Git repository and RStudio project. I like to have a one-to-one relationship of Git repositories and RStudio projects. In this project I’ve got four subfolders:</p>
<ul>
<li><code>R</code></li>
<li><code>prep</code></li>
<li><code>data</code></li>
<li><code>report-1</code></li>
</ul>
<p>The <code>R</code> folder has two scripts:</p>
<ul>
<li><code>corp-palette.R</code> which defines the corporate font and colour scheme to be used in graphics created by R</li>
<li><code>build_doc.R</code> which defines a function to render the R Markdown file into HTML (more on why this is needed later).</li>
</ul>
<p>The <code>prep</code> folder in this case holds a single script which downloads a dataset from the web, imports it from its Excel format and does some minor data management tasks like defining additional columns for use in future analysis.</p>
<p>The <code>data</code> folder holds data – both the raw data downloaded from the web, and analysis-ready versions as <code>.rda</code> files. The Git project has been told (via the <code>.gitignore</code> file) to ignore data files so they don’t bloat up the source code repository but are created by the script in <code>prep</code>.</p>
<p>Finally, the <code>report-1</code> holds a file written in R Markdown (<code>report.Rmd</code>) and some other assets like the SVG of the corporate logo.</p>
<p>In a larger project I might have a separate <code>analysis</code> folder, with scripts doing various analytical tasks. In this case, all of that is done in R chunks in the <code>report.Rmd</code> file.</p>
<p>Now, with a project as simple as this I could have had it all in a single .Rmd file which could be distributed by itself, but that approach doesn’t scale up well. I intensely dislike using a big .Rmd file as my main workflow control. Getting on top of the caching of R chunks alone is a major cause of frustration. There are also challenges with working directories, although these have been mitigated by recent developments in the world of <code>knitr</code>. But mostly it’s just good practice to think of analytical projects beyond the trivial in size as <em>projects</em>, involving a portable <em>folder system</em> not just individual scripts.</p>
<p>In this approach, the .Rmd file itself doesn’t need to be (and isn’t) 100% reproducible, so I avoid the “knit” button in RStudio which spawns a fresh R session from scratch. Instead I ensure reproducibility of the project – I should be able to make a fresh clone on a fresh computer with the right R packages on it, source <code>build.R</code> in a fresh session and have it run. But the .Rmd file isn’t self-sufficient, and I don’t think that’s a reasonable expectation in a big project (bigger than this toy).</p>
<p>This approach also works well in the common situation that a single project has multiple outputs eg a couple of reports, a Shiny app and a presentation. It makes little sense for each report and presentation to be self-sufficient and repeat tasks that are really one-off project tasks.</p>
<p>There’s an R script in the root directory of the project called <code>build.R</code> which basically runs scripts in the other folders in the correct order to re-create the whole exercise from scratch. Here’s what that script looks like. Notice I’ve tried to make it as aware of the environment as possible; for example, it doesn’t matter what order the files in the <code>R</code> subfolder are run in, so it just finds all the files there and runs them in alphabetical order. This means I don’t need to change the <code>build.R</code> script when I put a new script in the <code>R</code> directory.</p>
<figure>
<pre><code data-lang="r"><span># ./build.r
# This file downloads and munges data and builds the report/s for the project from scratch
# Peter Ellis 6 September 2017
</span><span>
</span><span>library</span><span>(</span><span>rmarkdown</span><span>)</span><span>
</span><span>library</span><span>(</span><span>ggplot2</span><span>)</span><span>
</span><span>library</span><span>(</span><span>scales</span><span>)</span><span>
</span><span>library</span><span>(</span><span>openxlsx</span><span>)</span><span>
</span><span>library</span><span>(</span><span>tidyverse</span><span>)</span><span>
</span><span>library</span><span>(</span><span>stringr</span><span>)</span><span>
</span><span>library</span><span>(</span><span>ggseas</span><span>)</span><span> </span><span># for seasonal adjustment on the fly
</span><span>library</span><span>(</span><span>forcats</span><span>)</span><span> </span><span># for munging factors
</span><span>library</span><span>(</span><span>extrafont</span><span>)</span><span> </span><span># in case running on windows
</span><span>library</span><span>(</span><span>stringi</span><span>)</span><span> </span><span># for generating pseudo lating lorem ipsum text
</span><span>
</span><span># Run all the files in the &quot;R&quot; folder, which create project assets
# like the corporate colours and the function we use to build documents.
</span><span>assets</span><span> </span><span>&lt;-</span><span> </span><span>list.files</span><span>(</span><span>path</span><span> </span><span>=</span><span> </span><span>&quot;R&quot;</span><span>,</span><span> </span><span>pattern</span><span> </span><span>=</span><span> </span><span>&quot;\\.R$&quot;</span><span>,</span><span> </span><span>full.names</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span><span>
</span><span>created_assets</span><span> </span><span>&lt;-</span><span> </span><span>lapply</span><span>(</span><span>assets</span><span>,</span><span> </span><span>source</span><span>)</span><span>
</span><span>rm</span><span>(</span><span>assets</span><span>,</span><span> </span><span>created_assets</span><span>)</span><span>
</span><span># download, reshape, and save the data
</span><span>source</span><span>(</span><span>&quot;prep/download-mrtes.R&quot;</span><span>)</span><span>
</span><span># load in the data (not really necessary)
</span><span>load</span><span>(</span><span>&quot;data/mrtes.rda&quot;</span><span>)</span><span>
</span><span># build the actual report. Note that the build will happen in the user's home directory (~).
</span><span>build_doc</span><span>(</span><span>subdir</span><span> </span><span>=</span><span> </span><span>&quot;report-1&quot;</span><span>)</span></code></pre>
</figure>
<h2>R Markdown with RStudio Server on a mapped network drive</h2>
<p>I’m pretty sure there’s a bug associated with the combination of RMarkdown, RStudio Server, Pandoc and mapped network drives. The long and the short of it is that <code>rmarkdown::render(&quot;document.Rmd&quot;)</code> will fail when asked to build a stand-alone HTML file if <code>document.Rmd</code> is on a mapped network drive. I really needed an emailable stand-alone HTML file, and at work my only access to R was on RStudio Server; and mapped network drives the only ones RStudio could see that I could access from the Windows file system.</p>
<p>I got past that problem with the following workaround, which made use of the fact that the RStudio Server was set up so I had a home directory (~) which, while not visible to Windows, I could save things in and navigate to and from in the R environment. So my approach was:</p>
<ul>
<li>copy all the files I need from the <code>report-1</code> project sub-folder to my home directory ~</li>
<li>change working directory to ~ and render the stand-alone HTML there</li>
<li>copy the HTML file back to the original <code>report-1</code> sub-folder, clean up the home directory, and return to the project root directory</li>
</ul>
<p>This is all done in the function <code>build_doc()</code>, which is one of the assets created at the beginning of the project:</p>
<figure>
<pre><code data-lang="r"><span>#' Build an R Markdown file that is in a subdirectory
#' #' Function to move all files in a subdirectory to the user's home directory, build the markdown file there,
#' and return the built version to the original subdirectory. Why would you want to do this? Because
#' R Markdown doesn't build nicely on RStudio Server on a mapped network drive due to a bug in Pandoc, so
#' sometimes you need to move everything to somewhere else.
#' #' @param subdir sub directory (relative to the project directory) holding a report and its necessary files
#' @param report_name name of the report, excluding the .Rmd suffix.
#' @param ... other arguments to be passed to rmarkdown::render()
#' @author Peter Ellis
</span><span>build_doc</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>subdir</span><span> </span><span>=</span><span> </span><span>&quot;report&quot;</span><span>,</span><span> </span><span>report_name</span><span> </span><span>=</span><span> </span><span>&quot;report&quot;</span><span>,</span><span> </span><span>...</span><span>){</span><span>
</span><span>proj_dir</span><span> </span><span>&lt;-</span><span> </span><span>getwd</span><span>()</span><span>
</span><span>on.exit</span><span>(</span><span>setwd</span><span>(</span><span>proj_dir</span><span>))</span><span>
</span><span># copy all the files from the report's sub directory to the home directory
</span><span> </span><span>files</span><span> </span><span>&lt;-</span><span> </span><span>list.files</span><span>(</span><span>subdir</span><span>)</span><span>
</span><span>file.copy</span><span>(</span><span>paste0</span><span>(</span><span>subdir</span><span>,</span><span> </span><span>&quot;/&quot;</span><span>,</span><span> </span><span>files</span><span>),</span><span> </span><span>paste0</span><span>(</span><span>&quot;~/&quot;</span><span>,</span><span> </span><span>files</span><span>),</span><span> </span><span>overwrite</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span><span> </span><span># go to the home directory and render the report
</span><span> </span><span>setwd</span><span>(</span><span>&quot;~&quot;</span><span>)</span><span>
</span><span>render</span><span>(</span><span>paste0</span><span>(</span><span>report_name</span><span>,</span><span> </span><span>&quot;.Rmd&quot;</span><span>),</span><span> </span><span>...</span><span>)</span><span> </span><span># copy the built version of the document back to the project:
</span><span> </span><span>file.copy</span><span>(</span><span>paste0</span><span>(</span><span>report_name</span><span>,</span><span> </span><span>&quot;.html&quot;</span><span>),</span><span> </span><span>paste0</span><span>(</span><span>proj_dir</span><span>,</span><span> </span><span>&quot;/&quot;</span><span>,</span><span> </span><span>subdir</span><span>,</span><span> </span><span>&quot;/&quot;</span><span>,</span><span> </span><span>report_name</span><span>,</span><span> </span><span>&quot;.html&quot;</span><span>),</span><span> </span><span>overwrite</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span><span>
</span><span># clean up by deleting the copies of the files in the home directory:
</span><span> </span><span>file.remove</span><span>(</span><span>files</span><span>)</span><span>
</span><span># go back to the project:
</span><span> </span><span>setwd</span><span>(</span><span>proj_dir</span><span>)</span><span> </span><span>}</span></code></pre>
</figure>
<p>If you find that useful you can actually get it from my nascent <code>pssmisc</code> R package where I’m putting odds and pieces like this:</p>
<figure>
<pre><code data-lang="r"><span>devtools</span><span>::</span><span>install_github</span><span>(</span><span>&quot;ellisp/pssmisc-r-package/pkg&quot;</span><span>)</span><span>
</span><span>library</span><span>(</span><span>pssmisc</span><span>)</span></code></pre>
</figure>
<h2>Approximating corporate style in HTML</h2>
<h3>Setting up the document</h3>
<p>A few things I wanted in this situation I need to set up in the YAML front matter of the .Rmd file:</p>
<ul>
<li>a stand-alone HTML document</li>
<li>a dynamic and floating table of contents on the left of the screen</li>
<li>syntax highlighting that works with SQL (not used in my demo project, but my real one at work had to do this)</li>
<li>incorporate cascading style sheets w</li>
</ul>
<p>So here’s the first 14 lines of the R Markdown <code>./report-1/report.Rmd</code>:</p>
<div>
<pre><code>---
title: &quot;Demonstration page of R Markdown in combination with corporate theming&quot;
author: &quot;Flash Gordon, consultant economist&quot;
date: &quot;9 September 2017&quot;
output: 
  html_document:
    toc: true
    toc_depth: 3
    toc_float: true
    number_sections: true
    self_contained: yes
    css: corp-styles.css
    highlight: pygments
---
</code></pre>
</div>
<h3>Fonts and headings with CSS</h3>
<p>This takes us to the file of Cascading Style Sheet instructions, <code>corp-styles.css</code>, sitting in the same folder as the report (this is probably a weakness to think through – better to have it in a central location somewhere). I’m no CSS expert but this is simple enough. I worked out the correct colours of headings and their sizes from the corporate Word templates, and converted them from point sizes to the percentage size relative to normal text. Colours and fonts in the below have been made up for this example:</p>
<figure>
<pre><code data-lang="css"><span>body</span> <span>{</span>
  <span>font-family</span><span>:</span> <span>Calibri</span><span>,</span> <span>helvetica</span><span>,</span> <span>sans-serif</span><span>;</span>
<span>}</span>

<span>h1</span> <span>{</span>
  <span>color</span><span>:</span> <span>rgb</span><span>(</span><span>226</span><span>,</span> <span>192</span><span>,</span> <span>78</span><span>);</span>
  <span>font-size</span><span>:</span> <span>127%</span><span>;</span>
<span>}</span>

<span>.title</span> <span>{</span>
  <span>margin-right</span><span>:</span> <span>200px</span><span>;</span>
<span>}</span>

<span>h2</span> <span>{</span>
  <span>color</span><span>:</span> <span>rgb</span><span>(</span><span>112</span><span>,</span> <span>111</span><span>,</span> <span>111</span><span>);</span>
  <span>font-size</span><span>:</span> <span>121%</span><span>;</span>
<span>}</span>

<span>h3</span> <span>{</span>
  <span>font-size</span><span>:</span> <span>109%</span><span>;</span>
  <span>font-weight</span><span>:</span> <span>bold</span><span>;</span>
<span>}</span>

<span>h4</span> <span>{</span>
  <span>font-size</span><span>:</span> <span>100%</span><span>;</span>
  <span>font-weight</span><span>:</span> <span>bold</span><span>;</span>
  <span>font-style</span><span>:</span> <span>italic</span><span>;</span>
<span>}</span>

<span>.watermark</span> <span>{</span>
  <span>opacity</span><span>:</span> <span>0.2</span><span>;</span>
  <span>position</span><span>:</span> <span>fixed</span><span>;</span>
  <span>top</span><span>:</span> <span>50%</span><span>;</span>
  <span>left</span><span>:</span> <span>50%</span><span>;</span>
  <span>font-size</span><span>:</span> <span>500%</span><span>;</span>
  <span>color</span><span>:</span> <span>#00407d</span><span>;</span>
<span>}</span></code></pre>
</figure>
<p>In my real world example I had some other things in there too, such as table formatting.</p>
<h3>Adding a logo</h3>
<p>As well as the headings and the body, notice the definition of the style of the <code>.title</code> class. This is the one-off element that is the title of the whole report. I give it a wide right margin of 200 pixels so there is room for my hideous made-up corporate logo in the top right. That logo is in the main <code>report.Rmd</code> file with the code:</p>
<div>
<pre><code><img src="https://www.r-bloggers.com/r-markdown-for-documents-with-logos-watermarks-and-corporate-styles-by-ellis2013nz/logo.svg">
</code></pre>
</div>
<p>…and obviously the file logo.svg is in the same folder as the report.</p>
<h3>Adding a watermark</h3>
<p>I wanted a watermark saying “DRAFT” in pale letters that would always be visible for readers. This worked quite well and was fairly simple. I just needed to include the single line below in my main <code>report.Rmd</code>, creating a div of class “watermark”. The CSS to force objects of this class be fixed in the middle of the page, large in size and opaque is in the <code>.watermark {...}</code> code in the <code>corp-styles.css</code> file already shown.</p>
<div>
<pre><code><div>DRAFT</div>
</code></pre>
</div>
<h2>Graphics</h2>
<p>The final thing to mention is the styling of the graphics produced by R itself. This is defined in the file <code>corp-palette.R</code>, already mentioned, which is run at the beginning of the project. It creates an object <code>corp_palette</code> to hold my hypothetical corporate colours for statistical graphics, and makes them the default discrete colour scale for <code>ggplot2</code>. It also sets an appropriate theme and font, and makes the font the default for the text geom.</p>
<figure>
<pre><code data-lang="r"><span># ./R/corp-palette.R
# Defines font and a hypothetical corporate palette, and makes them ggplot2 defaults
</span><span>
</span><span>corp_font</span><span> </span><span>&lt;-</span><span> </span><span>&quot;Calibri&quot;</span><span>
</span><span>theme_set</span><span>(</span><span>theme_minimal</span><span>(</span><span>base_family</span><span> </span><span>=</span><span> </span><span>corp_font</span><span>))</span><span>
</span><span>corp_palette</span><span> </span><span>&lt;-</span><span> </span><span>c</span><span>(</span><span>&quot;#800000&quot;</span><span>,</span><span> </span><span>&quot;#00004d&quot;</span><span>,</span><span> </span><span>&quot;#009900&quot;</span><span>,</span><span> </span><span>&quot;#8c1aff&quot;</span><span>,</span><span> </span><span>&quot;#5c85d6&quot;</span><span>,</span><span> </span><span>&quot;#996600&quot;</span><span>)</span><span>
</span><span>update_geom_defaults</span><span>(</span><span>&quot;text&quot;</span><span>,</span><span> </span><span>list</span><span>(</span><span>family</span><span> </span><span>=</span><span> </span><span>corp_font</span><span>,</span><span> </span><span>colour</span><span> </span><span>=</span><span> </span><span>corp_palette</span><span>[</span><span>1</span><span>]))</span><span>
</span><span>scale_colour_discrete</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>...</span><span>)</span><span> </span><span>scale_colour_manual</span><span>(</span><span>...</span><span>,</span><span> </span><span>values</span><span> </span><span>=</span><span> </span><span>corp_palette</span><span>)</span><span>
</span><span>scale_fill_discrete</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>...</span><span>)</span><span> </span><span>scale_fill_manual</span><span>(</span><span>...</span><span> </span><span>,</span><span> </span><span>values</span><span> </span><span>=</span><span> </span><span>corp_palette</span><span>)</span></code></pre>
</figure>
<p>That means I don’t need to specify the colours and fonts for individual charts in my R Markdown file.</p>
<h2>End result</h2>
<p>Enjoy:</p>
<ul>
<li><a rel="nofollow" href="http://ellisp.github.io/presentations/rmarkdown-styled-demo.html" target="_blank">built R Markdown -> HTML report</a> with correct fonts, colours (headings and graphs), logo and draft watermark</li>
<li><a rel="nofollow" href="https://github.com/ellisp/rmarkdown-corporate-eg" target="_blank">repository of source code</a></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://ellisp.github.io/blog/2017/09/09/rmarkdown"> Peter's stats stuff - R</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/D6QLRwcsz0E" height="1"></a></div>