R Reporting Part 8: Using LaTeX to Create Posters
This is the eigth of a series of articles on how to use R, RStudio and TexMaker to prepare presentations and batch jobs for automated reporting on a web server or Microsoft SharePoint server. The series is based upon the presentation that I did at the February 27, 2016 Dallas R User Group Meetup. Because the presentation was primarily a demonstration, there really isn’t a presentation to distribute; this series covers the topics from the presentation/demonstration. The series will eventually include the following articles as I complete them over the next couple of weeks:
- R Reporting Part 1: Tools
- R Reporting Part 2: Choosing the Right Markup for the Task
- R Reporting Part 3: Using Rhtml for Batch Web Reporting
- R Reporting Part 4: Using Markdown for Interactive Presentations
- R Reporting Part 5: Using LaTeX/Beamer for PDF Presentations
- R Reporting Part 6: Using LaTeX for PDF Articles
- R Reporting Part 7: Converting R Documents to E-books
- R Reporting Part 8: Using LaTeX to Create Posters
The series of articles describes the process for daily batch jobs that generate the Daily Econometric Graphs web page which includes links to the same econometric charts in several formats, all generated through the same R code:
- Econometric graphs in PDF form for use as slides on a projector
- Econometric graphs in PDF form for printing
- Econometric graphs in EPUB format
- Econometric graphs in Kindle AZW3 format
- Econometric graphs in A0 poster format
All of the examples are based upon the knitr
R package; you should reference the knitr
documentation, as this article is not a replacement for the knitr
documentation.
Example source is available in images/documents/econometric_source.zip.
LaTeX Poster Styles
Because LaTeX was written by and for academics and professionals in math and science who need to create posters for conferences and other displays, several authors have created LaTeX packages to make it easy to create posters. Here are a few of the major packages:
- Baposter from Brian Amberg is easy to use but has a relatively fixed display style.
- Beamerposter uses Beamer style operations.
- A0poster is perhaps the most flexible of the various poster packages, but with flexibility comes some complexity.
The example that follows will use BAposter, as it is probably the easiest to get working. The example poster is a PDF file Useful Econometrics Poster.
BAPoster Example
The code for the example poster uses the knitr chunk syntax discussed earlier in this series of articles in R Reporting Part 3: Using Rhtml for Batch Web Reporting and set up using the read_chunk("econometric_charts_chunks.R")
call in the prologue of the LaTeX/knitr file:
<<prolog,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE,dev=c('pdf','png','jpeg')>>=
#install.packages(c("dplyr","magrittr","assertr","ggvis","googleVis","htmlwidgets","networkD3","rCharts","qtlcharts","dygraphs","d3heatmap"))
require(ggplot2)
require(dplyr)
require(magrittr)
require(assertr)
require(ggplot2)
require(fImport)
require(reshape2)
require(scales)
require(knitr)
#library(RCurl)
setwd("~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R")
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
@
\documentclass[a0paper,portrait]{baposter}
\usepackage{color}
\definecolor{mssDeepBlue}{rgb}{0.1367188,0.375,0.5742188} % new RGB values
\definecolor{mssCyan}{rgb}{0.0,0.6210938,0.8515625}
\definecolor{mssGreen}{rgb}{0.4101562,0.7421875,0.15625}
\definecolor{mssCyanLight}{rgb}{0.0,0.3105469,0.4257812}
\usepackage{hyperref}
\usepackage{hyperxmp}
\usepackage{ifplatform}
%
%
%
\ifwindows
\newcommand{\mssPathDef}{C:/Users/bwmoore/Documents}
\else
\newcommand{\mssPathDef}{/home/bwmoore}
\fi
\begin{document}
\background{}
\begin{poster}{
background=none,
colspacing=0.7em,
textborder=roundedleft,
headerborder=none,
headershape=roundedright,
headerheight=0.134\textheight,% this defines height of box reserved for title, name, etc.
%another declarations
}
{}
{Useful Econometrics}
{Bruce Moore \\
Moore Software Services LLC \\
Coppell, TX USA \\
moorebw@mooresoftwareservices.com}
{ \includegraphics[width=7cm,angle=0]{"/home/bwmoore/svn_work/Consulting_Business/VG_Visuals/Dropbox/LOGOS/Logo - Tagline Below/MOORE LOGO Tagline"}}
\setlength\parindent{24pt}
%
%
%
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Column 1
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\headerbox{Purpose}{name=purpose,column=0,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
\paragraph{}This poster provides example econometrics to demonstrate using RStudio to generate a poster.
}
%
% Column 1 Box 2
%
\headerbox{Data Source}{name=dataSource,column=0,below=purpose,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
\paragraph{}The data for this poster was pulled from the St. Louis Federal Reserve FRED2 system using the fImport R package.
\paragraph{}The poster uses the \LaTeX\ \href{http://www.brian-amberg.de/uni/poster/}{BAposter} package and was composed in RStudio and generated using the knitr R package. It was formatted for A0 printing (33.11 by 46.81 inches), although BAposter supports other page sizes.
\paragraph{}Lists use the normal \LaTeX\ list itemize environment. For example, the data series used in this poster are
\begin{itemize}
\item Swap rates
\item Used Car and Rruck Consumer Price Index
\item Median Household Income
\item Unemployment Rate
\item Mortgage Delinquency
\end{itemize}
}
%
% Column 1 Box 3
%
\headerbox{Contact Information}{name=contact,column=0,below=dataSource,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
\begin{center}
Bruce Moore \\
bwmoore@mooresoftwareservices.com \\
+1 (972) 652-0254 \\
\includegraphics[width=.27\textwidth]{"/home/bwmoore/svn_work/Consulting_Business/sales_presentations/business_cards/images/bwmoore_tiny"}
\end{center}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Column 2
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\headerbox{Cost of Funds}{name=costOfFunds,column=1,span=2,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
<< costOfFunds,echo=FALSE,message=FALSE,warning=FALSE,error=FALSE,pdf.compress=TRUE,eval=TRUE,fig.path="images/figures/",dev=c("png","pdf","svg"),fig.width=6,fig.height=3,dpi=200>>=
@
%\includegraphics[width=\linewidth]{\mssPathDef/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R/images/figures/costOfFunds-1.png}
}
%
% Column 2 Box 2
%
\headerbox{Auto CPI}{name=autoCPI,column=1,below=costOfFunds,boxheaderheight=1.0cm,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
<< autoCPI,echo=FALSE,message=FALSE,warning=FALSE,error=FALSE,pdf.compress=TRUE,eval=TRUE,fig.path="images/figures/",dev=c("png","pdf","svg")>>=
@
}
%
% Column 2 Box 3
%
\headerbox{Mortgage Delinquency}{name=mortDelinquncy,column=1,below=autoCPI,boxheaderheight=1.0cm,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
<< mortDelinquency,echo=FALSE,message=FALSE,warning=FALSE,error=FALSE,pdf.compress=TRUE,eval=TRUE,fig.path="images/figures/",dev=c("png","pdf","svg")>>=
@
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Column 3
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Column 3 Box 2
%
\headerbox{Median Household Income}{name=medianHouseholdIncome,column=2,below=costOfFunds,boxheaderheight=1.0cm,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
<< medianHouseholdIncome,echo=FALSE,message=FALSE,warning=FALSE,error=FALSE,pdf.compress=TRUE,eval=TRUE,fig.path="images/figures/",dev=c("png","pdf","svg")>>=
@
}
%
% Column 3 Box 3
%
\headerbox{Unemployment}{name=unemployment,column=2,below=medianHouseholdIncome,boxheaderheight=1.0cm,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
<< medianHouseholdIncome,echo=FALSE,message=FALSE,warning=FALSE,error=FALSE,pdf.compress=TRUE,eval=TRUE,fig.path="images/figures/",dev=c("png","pdf","svg")>>=
@
}
\end{poster}
\end{document}
Set Up Defaults
The first step is to set the various global parameters for the poster, for complete information on the various options, see the BAPoster documentation.
\background{}
\begin{poster}{
background=none,
colspacing=0.7em,
textborder=roundedleft,
headerborder=none,
headershape=roundedright,
headerheight=0.134\textheight,% this defines height of box reserved for title, name, etc.
%another declarations
}
{}
{Useful Econometrics}
{Bruce Moore \\
Moore Software Services LLC \\
Coppell, TX USA \\
This email address is being protected from spambots. You need JavaScript enabled to view it.}
{ \includegraphics[width=7cm,angle=0]{"/home/bwmoore/svn_work/Consulting_Business/VG_Visuals/Dropbox/LOGOS/Logo - Tagline Below/MOORE LOGO Tagline"}}
\setlength\parindent{24pt}
The bracket pairs contain the following:
- The first bracket pair contains the key value options that set up the block shapes and other parameters
- The second bracket pair contains the eyecatcher text; this is not used on this poster
- The third bracket pair contains the poster title
- The fourth bracket pair contains the poster authors
- The final bracket pair contains the logo or header graphic for the poster
Creating a Text Box for a Single Column
BAPoster uses the headerbox
tag to generate each box on the poster:
\headerbox{Purpose}{name=purpose,column=0,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
\paragraph{}This poster provides example econometrics to demonstrate using RStudio to generate a poster.
}
The bracket pairs on the tag are as follows:
- The first bracket pair contains the text for the heading
- The second bracket pair contains the keywords for the tag, including these important tags:
name
is required and is needed to establish the relative position of boxes within a column.column
is required to determine in which column the box should be placedborderColor
and the other keywords are optional but will be used in almost all cases.- The third bracket pair contains the text for the box. This can include any LaTeX tags for tables, lists, math, as long as the output will fit on the poster.
Creating the Second Text Box in a Column
The second and subsequent text boxes in a column are identical to the first but must have a below
keyword to reference the text box that is immediately above:
\headerbox{Data Source}{name=dataSource,column=0,below=purpose,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
\paragraph{}The data for this poster was pulled from the St. Louis Federal Reserve FRED2 system using the fImport R package.
\paragraph{}The poster uses the \LaTeX\ \href{http://www.brian-amberg.de/uni/poster/}{BAposter} package and was composed in RStudio and generated using the knitr R package. It was formatted for A0 printing (33.11 by 46.81 inches), although BAposter supports other page sizes.
\paragraph{}Lists use the normal \LaTeX\ list itemize environment. For example, the data series used in this poster are
\begin{itemize}
\item Swap rates
\item Used Car and Rruck Consumer Price Index
\item Median Household Income
\item Unemployment Rate
\item Mortgage Delinquency
\end{itemize}
}
Creating a Text Box that Spans Columns
To emphasize a point, it will frequently be useful to create a text box that spans columns, as is done in the “Cost of Funds” block on this poster using the span
keyword:
\headerbox{Cost of Funds}{name=costOfFunds,column=1,span=2,borderColor=mssDeepBlue,headerColorOne=mssDeepBlue,headerColorTwo=mssDeepBlue,boxshade=none,headerFontColor=white}{
<< costOfFunds,echo=FALSE,message=FALSE,warning=FALSE,error=FALSE,pdf.compress=TRUE,eval=TRUE,fig.path="images/figures/",dev=c("png","pdf","svg"),fig.width=6,fig.height=3,dpi=200>>=
@
}
This text box incorporates R code that will be evaluated by the knitr
package. knitr
does not know the size of the LaTeX text box, so you will probably want to use the fig.width
and fig.height
keywords for the chunk to set the relative dimensions that you want for any graphics so that the proportions match what you need in the text box.
- Details
- Written by Bruce Moore
- Hits: 3696
R Reporting Part 7: Converting R Documents to E-books
This is the seventh of a series of articles on how to use R, RStudio and TexMaker to prepare presentations and batch jobs for automated reporting on a web server or Microsoft SharePoint server. The series is based upon the presentation that I did at the February 27, 2016 Dallas R User Group Meetup. Because the presentation was primarily a demonstration, there really isn’t a presentation to distribute; this series covers the topics from the presentation/demonstration. The series will eventually include the following articles as I complete them over the next couple of weeks:
- R Reporting Part 1: Tools
- R Reporting Part 2: Choosing the Right Markup for the Task
- R Reporting Part 3: Using Rhtml for Batch Web Reporting
- R Reporting Part 4: Using Markdown for Interactive Presentations
- R Reporting Part 5: Using LaTeX/Beamer for PDF Presentations
- R Reporting Part 6: Using LaTeX for PDF Articles
- R Reporting Part 7: Converting R Documents to E-books
- R Reporting Part 8: Using LaTeX to Create Posters
The series of articles describes the process for daily batch jobs that generate the Daily Econometric Graphs web page which includes links to the same econometric charts in several formats, all generated through the same R code:
- Econometric graphs in PDF form for use as slides on a projector
- Econometric graphs in PDF form for printing
- Econometric graphs in EPUB format
- Econometric graphs in Kindle AZW3 format
- Econometric graphs in A0 poster format
All of the examples are based upon the knitr
R package; you should reference the knitr
documentation, as this article is not a replacement for the knitr
documentation.
Example source is available in images/documents/econometric_source.zip.
Software Required
Creating epub files requires software that converts from html to epub format. Calibre is the one of the better open source tools for e-book generation and management. It is available for Linux, Windows and OS X. For converting LaTeX files to epub, it is necessary to create an HTML file as an intermediate step. There are several tools to do this; Latex2html is one of the tools that can do this and is arguably the best, but it is not being actively maintained. The LaTeX to HTML FAQ has a list of alternatives.
In looking at alternatives, it is helpful to use one that does not generate pages with headers and footers, as these can create problems during the epub generation process.
Creating an E-book from Rhtml
The first step in creating an E-book is to create an HTML file as input to the process. You can generate the document as the output from running an .RHTML
or by using one of several utilities for converting LaTeX files to HTML. The script below is a very simplified script to generate an epub. For simplicity, error checking and recovery are omitted:
#!/bin/bash
echo $HOME
cd ~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R
#
# Run RScript and knitr to generate the HTML file
#
/usr/bin/Rscript -e "require('knitr'); knit('econometric_charts_home_page.Rhtml')"
#
# Compress images
#
optipng images/figures/*.png
optipng *.png
#
# Use Calibre ebook-convert to convert the HTML file to an epub file
#
ebook-convert econometric_charts_home_page.html .epub --authors "Bruce Moore" --language en --no-default-epub-cover
#
# Upload to the web site
#
cd ~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R
scp -i /home/batchuser/.ssh/webuser econometric_charts_home_page_article/econometric_charts_home_page_article.epub This email address is being protected from spambots. You need JavaScript enabled to view it.:/home/webuser/www/images/documents/
Run RScript and Knitr
The first section of the script calls Rscript
to run R from the command line and pass two statements. The first is require('knitr')
while the second is to knit()
the Rhtml file which runs all of the R code and creates an HTML file.
#
# Run RScript and knitr to generate the HTML file
#
/usr/bin/Rscript -e "require('knitr'); knit('econometric_charts_home_page.Rhtml')"
Compress Images
The second segment uses optipng
to compress the .png
images that are created as graphics when running the Rhtml file:
#
# Compress images
#
optipng images/figures/*.png
optipng *.png
Ebook-convert
The third segment uses the ebook-convert
program from Calibre to create the epub file. There are numerous options for the ebook-convert
command but the --authors
, --language
and --no-default-epub-cover
options are a minimal set. The first two are self explainatory and are useful for all files. The --no-default-epub-cover
option is useful for input files that have content that generates a good cover page, or where no cover page is needed.
#
# Use Calibre ebook-convert to convert the HTML file to an epub file
#
ebook-convert econometric_charts_home_page.html .epub --authors "Bruce Moore" --language en --no-default-epub-cover
Upload to Server
The final segment is a command to upload files to a web server or other server. In this case, the scp
secure copy command is used. In this use, it is assumed that public key authentication has previously been configured. The -i
option is not normally needed for interactive use, but is necessary for reliable use under cron. The -i
option points to the private key file to be used for authentication.
#
# Upload to the web site
#
cd ~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R
scp -i /home/batchuser/.ssh/webuser econometric_charts_home_page_article/econometric_charts_home_page_article.epub This email address is being protected from spambots. You need JavaScript enabled to view it.:/home/webuser/www/images/documents/
Converting LaTeX to Epub
When using a LaTeX input file, there is one additional step in between the RScript
and ebook-convert
segments. Option -split +0
causes the output to be placed into a single HTML file rather than splitting it into files based upon sections.
#
# Generate the epub version of the article
#
latex2html -split +0 econometric_charts_home_page_slides.tex
- Details
- Written by Bruce Moore
- Hits: 2266
R Reporting Part 5: Using LaTeX/Beamer for PDF Presentations
This is the fifth of a series of articles on how to use R, RStudio and TexMaker to prepare presentations and batch jobs for automated reporting on a web server or Microsoft SharePoint server. The series is based upon the presentation that I did at the February 27, 2016 Dallas R User Group Meetup. Because the presentation was primarily a demonstration, there really isn’t a presentation to distribute; this series covers the topics from the presentation/demonstration. The series will eventually include the following articles as I complete them over the next couple of weeks:
- R Reporting Part 1: Tools
- R Reporting Part 2: Choosing the Right Markup for the Task
- R Reporting Part 3: Using Rhtml for Batch Web Reporting
- R Reporting Part 4: Using Markdown for Interactive Presentations
- R Reporting Part 5: Using LaTeX/Beamer for PDF Presentations
- R Reporting Part 6: Using LaTeX for PDF Articles
- R Reporting Part 7: Converting R Documents to E-books
- R Reporting Part 8: Using LaTeX to Create Posters
The series of articles describes the process for daily batch jobs that generate the Daily Econometric Graphs web page which includes links to the same econometric charts in several formats, all generated through the same R code:
- Econometric graphs in PDF form for use as slides on a projector
- Econometric graphs in PDF form for printing
- Econometric graphs in EPUB format
- Econometric graphs in Kindle AZW3 format
- Econometric graphs in A0 poster format
All of the examples are based upon the knitr
R package; you should reference the knitr
documentation, as this article is not a replacement for the knitr
documentation.
Example source is available in images/documents/econometric_source.zip.
Using Rnw for LaTeX/Beamer Presentations
LaTeX’s Beamer presentations allow easy use of math symbols, cross referencing, citation, and a create presentation table of contents. To create a LaTeX/Beamer presentation create an .Rnw
file as shown in Figure 1. RStudio will populate the file with the basic LaTeX tags as shown in Figure 2, but for a Beamer presentation, you can probably start with something like the tags in Figure 3.

\documentclass{article}
\begin{document}
\end{document}
\documentclass{beamer}
\title[Selected Econometrics]{Selected Econometrics for \today}
\subject{Selected Econometrics for \today}
%\copyright{Copyright \copyright 2014 by Moore Software Services, LLC. All rights reserved.}
\author[Bruce Moore]{Bruce Moore, DEng}
\institute[Moore Software Services]{Moore Software Services, LLC\\
P.O. Box 183\\
Coppell, TX 75019\\
(972) 652-0254\\
\texttt{This email address is being protected from spambots. You need JavaScript enabled to view it.} \\
\texttt{www.mooresoftwareservices.com} \\
}
\date{\today}
\begin{document}
%
% Titlepage
%
\begin{frame}[plain]
\titlepage
\end{frame}
%\SweaveOpts{concordance=TRUE}
\section{Swap}
%
%
%
\begin{frame}[fragile]{Heading for slide 1}
\begin{itemize}
\item Item 1
\item Item 2
\end{itemize}
\end{frame}
\end{document}
Call all Needed Libraries in the Prologue knitr Chunk
Next, add the "prologue" in the file where all of the required R libraries are included and options are set:
<<prologue,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE>>=
#install.packages(c("dplyr","magrittr","assertr","ggvis","googleVis","htmlwidgets","networkD3","rCharts","qtlcharts","dygraphs","d3heatmap"))
require(ggplot2)
require(dplyr)
require(magrittr)
require(assertr)
require(ggplot2)
require(fImport)
require(reshape2)
require(scales)
#library(RCurl)
setwd("~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R")
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
@
It does not matter where you put this as long as it occurs before the first slide that uses R to generate the output. All of this should be familiar except for the lines
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
The options
line changes the download method used by the Rcurl
package (a dependency loaded by fImport) to one that works on my Linux machine, as the default download method does not work on my machine. The read_chunk
line is the one that is important for including code into Markdown presentations and reports.
When you create an R report that will be compiled by knitr
, you can either put the code inline, or create it in a separate .R
file that can be called from multiple .Rhtml, .Rmd, .RPres or .Rnw
files; knitr
reads these chunks from the file specified in the read_chunk("filename.R")
call at the beginning of your .Rhtml
or .Rnw
file. From a re-use perspective, the chunk method is very helpful.
“Prologue” is not a reserved word nor does knitr
require this label; this is just a personal standard for all of the .Rhtml
and .Rnw
files that I create.
Writing the Knitr Chunk File econometric_charts_chunks.R With an Interactive Graphic
The previous articles in this series talk about how to create the chunk file for reuse; see R Reporting Part 4: Using Markdown for Presentations for instructions on creating the chunk file.
Create a Slide and Call an R Chunk to Create a Graphic
Once the chunk file is ready, you can call it from your Beamer presentation:
%
%
%
\begin{frame}[fragile]{Swap rates are a useful proxy for top-of-market CD rates and for transfer prices}
<<costOfFunds,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE,fig.path="images/figures",out.height='0.6\\textheight'>>=
@
\footnote{Board of Governors of the Federal Reserve System (US), 1-Year Swap Rate [MSWP1], 2-Year Swap Rate [MSWP2], 3-Year Swap Rate [MSWP3], and 5-Year Swap Rate [MSWP5] retrieved from FRED, Federal Reserve Bank of St. Louis \url{https://research.stlouisfed.org/fred2/series/series_name}, \today.}
\end{frame}
Adding the Epilog
Finally, if there are things that you want to do after the R code for your graphics run and before pdflatex
runs, add a epilogue to run additional commands. This is a personal coding practice and is not a standard or requirement. I usually run optipng
or some other image compression utility as the last step in all of my Rhtml, Rmd and Rnw files:
<<epilogue,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE,fig.path="images/figures",out.width='\\textwidth',out.height='0.8\\textheight'>>=
system('optipng images/figures/*.png')
@
Running knitr
to Generate the HTML File
The final step is to run knitr
to process the file; to do this, click on the “Knit” icon at the top of the active tab in RStudio, as shown in Figure 2:
knitr
to generate the PDF file and all figures.
The output from this will be a PDF file that you can view on any machine without any dependencies. You cannot do interactive visualizations in Beamer.
- Details
- Written by Bruce Moore
- Hits: 3389
R Reporting Part 6: Using LaTeX for PDF Articles
This is the sixth of a series of articles on how to use R, RStudio and TexMaker to prepare presentations and batch jobs for automated reporting on a web server or Microsoft SharePoint server. The series is based upon the presentation that I did at the February 27, 2016 Dallas R User Group Meetup. Because the presentation was primarily a demonstration, there really isn’t a presentation to distribute; this series covers the topics from the presentation/demonstration. The series will eventually include the following articles as I complete them over the next couple of weeks:
- R Reporting Part 1: Tools
- R Reporting Part 2: Choosing the Right Markup for the Task
- R Reporting Part 3: Using Rhtml for Batch Web Reporting
- R Reporting Part 4: Using Markdown for Interactive Presentations
- R Reporting Part 5: Using LaTeX/Beamer for PDF Presentations
- R Reporting Part 6: Using LaTeX for PDF Articles
- R Reporting Part 7: Converting R Documents to E-books
- R Reporting Part 8: Using LaTeX to Create Posters
The series of articles describes the process for daily batch jobs that generate the Daily Econometric Graphs web page which includes links to the same econometric charts in several formats, all generated through the same R code:
- Econometric graphs in PDF form for use as slides on a projector
- Econometric graphs in PDF form for printing
- Econometric graphs in EPUB format
- Econometric graphs in Kindle AZW3 format
- Econometric graphs in A0 poster format
All of the examples are based upon the knitr
R package; you should reference the knitr
documentation, as this article is not a replacement for the knitr
documentation.
Example source is available in images/documents/econometric_source.zip.
Using Rnw for LaTeX/Beamer Presentations
LaTeX’s For most true automated reporting requirements, LaTex offers some very useful capabilities:
- Table of Contents
- List of Figures
- Footnotes, in-line citations and automated bibliography for data references
- Indexing
To create a LaTeX article, create an .Rnw
file as shown in Figure 1. RStudio will populate the file with the basic LaTeX tags as shown in Figure 2, but for a more realistic document, you can probably start with something like the tags in Figure 3.

\documentclass{article}
\begin{document}
\end{document}
\documentclass{article} %% Print version for presentation
%
% Printing options
%
\usepackage[]{tikz}
\usepackage{hyperref}
\usepackage{hyperxmp}
\usepackage{multimedia} % allows video?
\usepackage{ifplatform}
\usepackage{verbatim}
\usepackage{endnotes}
%\let\enotesize=\tiny
%\let\footnote=\endnote
%
% Determine the OS and set the path prefix
% Note that \iflinux always retURs false unless shell escape is enabled
%
\ifwindows
\newcommand{\mssPathDef}{C:/Users/bwmoore/Documents}
\else
\newcommand{\mssPathDef}{/home/bwmoore}
\fi
%\iflinux
%\fi
%
%
\hypersetup{
pdfcopyright={Copyright \copyright \the\year by Moore Software Services, LLC. All rights reserved.}
pdfsubject={}
}
%
%
%
\begin{document}
\begin{titlepage}
\begin{center}
\begin{huge}
\textbf{Selected Econometrics for \today} \\
\end{huge}
Bruce Moore, DEng \\
Moore Software Services, LLC \\
P.O. Box 183\\
Coppell, TX 75019\\
(972) 652-0254\\
\texttt{This email address is being protected from spambots. You need JavaScript enabled to view it.} \\
\href{https://www.mooresoftwareservices.com}{www.mooresoftwareservices.com} \\
%\includegraphics[height=\textheight]{\mssPathDef/svn_work/Consulting_Business/VG_Visuals/IncludeLogos/MOORE_LOGO_Tagline.pdf}
\includegraphics[width=\textwidth]{\mssPathDef/svn_work/Consulting_Business/VG_Visuals/IncludeLogos/MOORE_LOGO_Tagline.png}
\includegraphics[scale=3.0]{\mssPathDef/svn_work/Consulting_Business/sales_presentations/business_cards/images/bwmoore_d600.png}
\end{center}
\end{titlepage}
\tableofcontents
\listoffigures
\end{document}
Figure 3 has an example of how to prepare all of the major items in a large document, but this is just touching the tip of the iceberg on what can be done with LaTeX. The main unusual feature in this example is the /ifwindows
segment; this sets up a variable with a path structure for my windows laptop or my Ubuntu desktop, so that I can work on the files on either machine.
For more information on LaTeX tags, read one or more of the following tutorials and books:
- Beginning LaTeX at Cornell University
- LaTeX Tutorial at Rensselaer Polytechnic Institute
- LaTeX Documentation at the LaTeX project
Call all Needed Libraries in the Prologue knitr Chunk
Next, add the "prologue" in the file where all of the required R libraries are included and options are set:
<<prologue,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE>>=
#install.packages(c("dplyr","magrittr","assertr","ggvis","googleVis","htmlwidgets","networkD3","rCharts","qtlcharts","dygraphs","d3heatmap"))
require(ggplot2)
require(dplyr)
require(magrittr)
require(assertr)
require(ggplot2)
require(fImport)
require(reshape2)
require(scales)
#library(RCurl)
setwd("~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R")
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
@
It does not matter where you put this as long as it occurs before the first slide that uses R to generate the output. All of this should be familiar except for the lines
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
The options
line changes the download method used by the Rcurl
package (a dependency loaded by fImport) to one that works on my Linux machine, as the default download method does not work on my machine. The read_chunk
line is the one that is important for including code into Markdown presentations and reports.
When you create an R report that will be compiled by knitr
, you can either put the code inline, or create it in a separate .R
file that can be called from multiple .Rhtml, .Rmd, .RPres or .Rnw
files; knitr
reads these chunks from the file specified in the read_chunk("filename.R")
call at the beginning of your .Rhtml
or .Rnw
file. From a re-use perspective, the chunk method is very helpful.
“Prologue” is not a reserved word nor does knitr
require this label; this is just a personal standard for all of the .Rhtml
and .Rnw
files that I create.
Writing the Knitr Chunk File econometric_charts_chunks.R With an Interactive Graphic
The previous articles in this series talk about how to create the chunk file for reuse; see R Reporting Part 4: Using Markdown for Presentations for instructions on creating the chunk file.
Create a Section in the Article and Call an R Chunk to Create a Graphic
Once the chunk file is ready, you can call it from your article:
\section{Pricing}
There are several econometric series available on the St. Louis Federal Reserve System FRED2 web site that are useful in setting prices for loans and deposits. This section contains plots of recent downloads of common series from FRED2.
\subsection{Swap Rates}
Swap rates are a useful proxy for top-of-market CD rates and for transfer prices, since an institution can both borrow and deposit funds at approximately the swap rate. Rational institutions with access to markets rarely go significantly higher than the swap rate. Typically, wholesale funders like the Federal Home Loan Bank (FHLB) offer rates that are generally about 50 basis points higher than the swap rate; it is very unusual for an institution to gather deposits at rates above these rates.
<<costOfFunds,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE,fig.path="images/figures",fig.cap="Swap rates are a useful proxy for top-of-market CD rates and for transfer prices.",dev=c('pdf','png','jpeg')>>=
@
\footnote{Board of Governors of the Federal Reserve System (US), 1-Year Swap Rate [MSWP1], 2-Year Swap Rate [MSWP2], 3-Year Swap Rate [MSWP3], and 5-Year Swap Rate [MSWP5] retrieved from FRED, Federal Reserve Bank of St. Louis \url{https://research.stlouisfed.org/fred2/series/series_name}, \today.}
%
%
%
\newpage
\section{Severity of Loss}
This section contains plot of econometrics that are useful in forecasting the severity of loss when a loss occurs on loan products.
\subsection{CPI for Used Cars and Trucks}
The CPI for Used Cars and Trucks is useful in forecasting the severity of loss for auto loans. As the index increases, the severity of loss will decrease, while a decreasing index will potentially cause an increase in the severity of loss. Understanding the seasonality in the index can help in decision making on whether to hold a vehicle in inventory for one or two months to get a better price at auction or to sell the vehicle as quickly as possible during periods when the market is expected to decline.
<<autoCPI,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE,fig.path="images/figures",fig.cap="The CPI for Used Cars and Trucks is useful in forecasting the severity of loss for auto loans.",dev=c('pdf','png','jpeg')>>=
@
\footnote{US. Bureau of Labor Statistics, Consumer Price Index for All Urban Consumers: Used cars and trucks [CUUR0000SETA02], retrieved from FRED, Federal Reserve Bank of St. Louis \url{https://research.stlouisfed.org/fred2/series/CUUR0000SETA02}, \today.}
Adding Mid-sentence R Output
If you are preparing a report that will have to be re-run with new data on a regular basis, you may want to use number generated by R in the report. Knitr (or Sweave) make this easy using the \Sexpr{}
tag. In most cases, you will want to use the round
or format
functions to limit the number of digits. The I()
function is mainly useful for Rhtml files, where it removes a code-like font; this is included here only because you may run across it in files that have been converted from .Rhtml to .Rnw.
\section{Summary}
<<sumP,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE,fig.path="images/figures",fig.cap="Mortgage Delinquency is useful in forecasting frequency of loss.",dev=c('pdf','png','jpeg')>>=
swpTs<-fredSeries(c("MSWP5","MSWP3","MSWP2","MSWP1"),nDaysBack=365*10,to=Sys.timeDate())
swpTs$dateVal = as.Date(rownames(swpTs))
swpDf <- data.frame(swpTs)
swpDf$dateVal <- as.character(swpDf$dateVal) # melt doesn't work with Date data types
swpDf$dateVal <- as.Date(swpDf$dateVal) # ggplot's scale_x_date doesn't work with character data types
colnames(swpDf)[2] <- "Series"
max5year <- mean(swpDf$MSWP5)
max1year <- mean(swpDf$MSWP1)
summary(swpDf)
@
There are several different ways to format output for in-line R:
\begin{itemize}
\item The mean rate in the 5-year swap series is \Sexpr{mean(swpDf$MSWP5)}.
\item The mean rate in the 5-year swap series is \Sexpr{round(mean(swpDf$MSWP5),2)}.
\item The mean rate in the 5-year swap series is \Sexpr{format(round(mean(swpDf$MSWP5),2), nsmall=0)}.
\item The mean rate in the 5-year swap series is \Sexpr{I(format(round(mean(swpDf$MSWP5),2), nsmall=0))}.
\end{itemize}
Adding the Epilogue
Finally, if there are things that you want to do after the R code for your graphics run and before pdflatex
runs, add a epilogue to run additional commands. This is a personal coding practice and is not a standard or requirement. I usually run optipng
or some other image compression utility as the last step in all of my Rhtml, Rmd and Rnw files:
<<epilogue,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE,fig.path="images/figures",out.width='\\textwidth',out.height='0.8\\textheight'>>=
system('optipng images/figures/*.png')
@
Running knitr
to Generate the HTML File
The final step is to run knitr
to process the file; to do this, click on the “Knit” icon at the top of the active tab in RStudio, as shown in Figure 2:
knitr
to generate the PDF file and all figures.
The output from this will be a PDF file that you can view on any machine without any dependencies. You cannot do interactive visualizations in Beamer.
- Details
- Written by Bruce Moore
- Hits: 2814
R Reporting Part 4: Using Markdown for Presentations
This is the fourth of a series of articles on how to use R, RStudio and TexMaker to prepare presentations and batch jobs for automated reporting on a web server or Microsoft SharePoint server. The series is based upon the presentation that I did at the February 27, 2016 Dallas R User Group Meetup. Because the presentation was primarily a demonstration, there really isn’t a presentation to distribute; this series covers the topics from the presentation/demonstration. The series will eventually include the following articles as I complete them over the next couple of weeks:
- R Reporting Part 1: Tools
- R Reporting Part 2: Choosing the Right Markup for the Task
- R Reporting Part 3: Using Rhtml for Batch Web Reporting
- R Reporting Part 4: Using Markdown for Interactive Presentations
- R Reporting Part 5: Using LaTeX/Beamer for PDF Presentations
- R Reporting Part 6: Using LaTeX for PDF Articles
- R Reporting Part 7: Converting R Documents to E-books
- R Reporting Part 8: Using LaTeX to Create Posters
The series of articles describes the process for daily batch jobs that generate the Daily Econometric Graphs web page which includes links to the same econometric charts in several formats, all generated through the same R code:
- Econometric graphs in PDF form for use as slides on a projector
- Econometric graphs in PDF form for printing
- Econometric graphs in EPUB format
- Econometric graphs in Kindle AZW3 format
- Econometric graphs in A0 poster format
All of the examples are based upon the knitr
R package; you should reference the knitr
documentation, as this article is not a replacement for the knitr
documentation.
Example source is available in images/documents/econometric_source.zip.
Using Rmd for Interactive Presentations
The first step in creating the interactive presentation is to create the .Rmd
file in RStudio as shown in Figure 1. RStudio will prompt you for the output type as shown in Figure 2, where there are three choices:
- HTML (ioslides)–this type allows interactive graphics and math markup (using MathJax). The math markup is not portable to other machines unless the machine has either an Internet connection or has MathJax installed.
- HTML (Slidy)–this type allows interactive graphics and math markup (using MathJax). The math markup is not portable to other machines unless the machine has either an Internet connection or has MathJax installed.
- PDF (Beamer)–this type does not allow interactive graphics and math markup (using LaTeX). The math markup in the PDF file is portable to other machines.
You can change the output type later if you want.


Modify the Title and Other Header Information
The first step is to modify the header information in the Markdown file to set the title, author, output type and footer. The snippet below shows the major header settings that you are likely to need for a basic presentation. The incremental
setting allows you to step through the bullet points in a presentation. The use of “:” and indention in the header is syntactically important; the “:” is a line end terminator.
---
title: "Using RStudio for Presentations and Reports"
author: "Bruce Moore"
date: "February 26, 2016"
output:
ioslides_presentation:
incremental: true
footer: "Bruce Moore, Moore Software Services"
---
The Markdown Reference Guide has complete information on the options that you can include in the header.
Call all Needed Libraries in the Prologue knitr Chunk
Next, add the "prologue" in the file where all of the required R libraries are included and options are set:
‘‘‘{r,prologue,message=FALSE,echo=FALSE,error=FALSE,warning=FALSE}
require(ggplot2)
require(dplyr)
require(magrittr)
require(assertr)
require(ggplot2)
require(fImport)
require(reshape2)
require(scales)
require(googleVis)
#library(RCurl)
setwd("~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R")
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
‘‘‘
All of this should be familiar except for the lines
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
The options
line changes the download method used by the Rcurl
package (a dependency loaded by fImport) to one that works on my Linux machine, as the default download method does not work on my machine. The read_chunk
line is the one that is important for including code into Markdown presentations and reports.
When you create an R report that will be compiled by knitr
, you can either put the code inline, or create it in a separate .R
file that can be called from multiple .Rhtml, .Rmd, .RPres or .Rnw
files; knitr
reads these chunks from the file specified in the read_chunk("filename.R")
call at the beginning of your .Rhtml
or .Rnw
file. From a re-use perspective, the chunk method is very helpful.
“Prologue” is not a reserved word nor does knitr
require this label; this is just a personal standard for all of the .Rhtml
and .Rnw
files that I create.
Create a Slide and call the R Chunk to Generate the Graphic
The next step is to add the ##
tag followed by the slide heading and other Markdown tags for a slide. This is followed by the knitr
markup to call our code chunk from the econometric_charts_chunks.R
file:
‘‘‘{r, costOfFunds,fig.path="images/figures/",fig.width=7, fig.height=5,fig.dpi=100,message=FALSE,warning=FALSE,echo=FALSE,cache=FALSE}
‘‘‘
All R code in the .Rmd
file must be enclosed with the knitr
tags:
‘‘‘{r, }
and
‘‘‘
This is a special Markdown code delimiters that knitr
looks uses to identify and run any R code that is enclosed. Most of the knitr
options in this example are self explanatory, but the fig.path
option requires some discussion. By default, knitr
will create a figure
directory in whatever the root directory is–your home directory unless you otherwise set it, as was done in the prologue section in this example.
Writing the Knitr Chunk File econometric_charts_chunks.R With an Interactive Graphic
The last step is to add the R code to the generate the interactive graphic to the econometric_charts_chunks.R
so that knitr
will generate the graphic. In the .R
file, the costOfFundsInteractive
## ---- costOfFundsInteractive ----
label for the chuck must match the chunk label ## ---- costOfFundsInteractive ----
in the econometric_charts_chunks.R
file:
## ---- costOfFundsInteractive ----
#
# Make the figure with swap rates
#
swpTs<-fredSeries(c("MSWP5","MSWP3","MSWP2","MSWP1"),nDaysBack=365*10,to=Sys.timeDate())
swpTs$dateVal = as.Date(rownames(swpTs))
swpDf <- data.frame(swpTs)
swpDf$dateVal <- as.Date(swpDf$dateVal) # ggplot's scale_x_date doesn't work with character data types
colnames(swpDf)[2] <- "Series"
chart <- googleVis::gvisLineChart(data=swpDf
,xvar="dateVal",yvar=c("MSWP5","MSWP2","MSWP1")
,options=list(width=800,height=600,gvis.editor="Edit",title='Swap Rates'))
#plot(chart) # use this for console debugging
print(chart) # use this for output in Markdown
In the .Rmd
file
While debugging in the console, uncomment the plot
command; for output in knitr
use the plot
statement.
Adding the Epilog
The final chunk in the presentation file is probably a good practice or perhaps a time saving measure but is not a requirement; an epilogue to run image compression on any image files that were created by the script:
‘‘‘{r, epilogue,echo=FALSE,message=FALSE,warning=FALSE,cache=FALSE}
system('optipng("images/figures/*.png")')
‘‘‘
The optipng
utility compresses .png
files and will improve the load time for your page. If you choose to generate .jpg
or other file types, you can call other utilities to compress them.
Running knitr
to Generate the HTML File
The final step is to run knitr
to process the file; to do this, click on the “Knit” icon at the top of the active tab in RStudio, as shown in Figure 2:
knitr
to generate the HTML file and all figures.
The output from this will be an HTML file that you can open in a browser. If you use interactive visualizations that depend upon libraries from the web, you may have problems running your presentation without an Internet connection, so make sure to test your presentation with networking turned off to understand what will and will not render or work.
- Details
- Written by Bruce Moore
- Hits: 3249