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: 2853
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: 3429
R Reporting Part 3: Using Rhtml for Batch Web Reporting
This is the third of a series of article 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 Rhtml for Batch Web Reporting
The first step in creating the batch report is to create a .Rhtml
file in RStudio as shown in Figure 1:

Call all Needed Libraries in the prologue knitr Chunk
Next, strip out (or reuse) the default HTML with the tags for the "prologue" in the file where all of the required R libraries are included:
<!--begin.rcode prologue,fig.path="images/figures/",fig.width=7, fig.height=5,fig.dpi=100,message=FALSE,warning=FALSE,echo=FALSE
setwd("~/svn_work/Consulting_Business/web_site/articles/econometric_charts/src/R")
library(ggplot2)
library(fImport)
library(reshape2)
library(scales)
options('download.file.method'='wget')
read_chunk("econometric_charts_chunks.R")
#R.Version()
end.rcode-->
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 batch reporting.
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 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 Figure and call the R Chunk to Generate the Graphic
The next step is to add the <figure>
and related tags, with the knitr
markup to call our code chunk from the econometric_charts_chunks.R
file:
<figure>
<figurecap>Cost of Funds Benchmark–One through five year swap Rates</figurecap>
<!--begin.rcode costOfFunds,fig.path="images/figures/",fig.width=7, fig.height=5,fig.dpi=100,message=FALSE,warning=FALSE,echo=FALSE,cache=FALSE
</figure>
All R code in the .Rhtml
file must be enclosed with the knitr
tags:
<!--begin.rcode
and
end.rcode-->
From and HTML perspective, this is a comment, but knitr
looks for these special comment delimiters 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. If you plan to upload this to a web server, you will need to create an image storage directory structure that matches the image directory structure on your web server. On my web server, the image directory for most articles is images/figures
. If you do not set the fig.path
, you will need to manually correct the .html
file that knitr
generates each time you upload everything.
Writing the Knitr Chunk File econometric_charts_chunks.R
The last step is to add the R code to the generate the graphic to the econometric_charts_chunks.R
so that knitr
will generate the graphic. In the .R
file, the costOfFunds
<!--begin.rcode costOfFunds
label for the chuck must match the chunk label ## ---- costOfFunds ----
in the econometric_charts_chunks.R
file:
#
## ---- costOfFunds ----
#
# Make the figure with swap rates
#
#swpTs<-fredSeries("MSWP1")
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
#summary(swpDf)
swpDf <- melt(swpDf)
swpDf$dateVal <- as.Date(swpDf$dateVal) # ggplot's scale_x_date doesn't work with character data types
colnames(swpDf)[2] <- "Series"
swpIntPlot <- ggplot(data=swpDf,aes(swpDf$dateVal,swpDf$value,group=swpDf$Series)) + geom_line()
#swpIntPlot + ggtitle("Swap Rates") + xlab("Date") + ylab("Rate") + scale_x_date()
swpIntPlot + ggtitle("Swap Rates") + xlab("Date") + ylab("Rate")+ scale_x_date() + geom_point(aes(color=Series)) + theme(panel.background = element_rect(colour="#f4f6f7"))
The remaining figures are added with similarly.
Adding the Epilog
The final chunk in the report file is probably a good practice or perhaps a time saving measure; an epilog to run image compression on any image files that were created by the script:
<!--begin.rcode epilog,echo=FALSE,message=FALSE,warning=FALSE,cache=FALSE
system('optipng("images/figures/*.png")')
end.rcode-->
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.
- Details
- Written by Bruce Moore
- Hits: 2777
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: 3290
Responsive Design for MathJax and Tables
Websites that require mathematics and tables increasingly need to be usable on mobile devices; an article on this site for an arcane accounting topic is pulled up on cell phones and tablets surprisingly frequently. Presumably, in the middle of a meeting of an accounting team meeting near the end of the quarter, someone starts frantically searching on “level yield loan fee amortization” and comes up with the article Effective Interest (Yield) Loan Fee Amortization. This article includes both a very wide table that originally caused iPhones to choose a font that was about 2 points or so. I found a way to force a smaller font for tables only based upon the screen resolution, but this was not entirely satisfactory, as the MathJax formula line-length still forced a small font size.
After some months of intermittent searching, I finally found the markup that makes tables and MathJax formulas usable on mobile devices:
<div style="overflow-x:auto;">
<table>
</table>
</div>
or in the case of MathJax,
<div style="overflow-x:auto;">
MathJax markup
</div>
Table Example
The table below is enclosed in the <div style="overflow-x:auto;">
block as shown above:
Level Yield Amortization Detailed Calculation | Level Yield | Level Yield Simplified Calculation | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Period | Principal | Payment | Interest | Applied Principal | Fee Balance | Fee Pseudo Payment | Fee Pseudo Interest | Applied Fee Principal Amortization Expense | Level Yield Asset | Yield After Fee Amortization | Amortization Expense Reduction to Contract Yield | Simplified Calculation of Amortization Expense Reduction to Contract Yield | Simplified Calculation of Amortization Expense |
0 | $10,000.00 | -$198.01 | $58.33 | -$139.68 | $1,000.00 | -$19.80 | $5.83 | -$13.97 | $11,000.00 | 6.36 | 0.64 | 0.64 | -$13.97 |
1 | $9,860.32 | -$198.01 | $57.52 | -$140.49 | $986.03 | -$19.80 | $5.75 | -$14.05 | $10,846.35 | 6.36 | 0.64 | 0.64 | -$14.05 |
2 | $9,719.83 | -$198.01 | $56.70 | -$141.31 | $971.98 | -$19.80 | $5.67 | -$14.13 | $10,691.81 | 6.36 | 0.64 | 0.64 | -$14.13 |
MathJax Example
The MathJax output below is enclosed in the <div style="overflow-x:auto;">
block as shown above:
- Details
- Written by Bruce Moore
- Hits: 2505