Chapter 10 Deployment

All this analysis does anyone little good unless you can deploy your findings in a easily retrievable format. Here, we look at a few options with the first being Markdown (the document you are reading was written in Markdown). Markdown has the benefits of being able to write to HTML, .pdf or MS Word and you can also write to RStudio’s slidify for presentations.

The next option we will look at is writing R output to PowerPoint and sending via Outlook. PowerPoint is the most used format for Corporate presentations, and Outlook the most widely used e-mail application in the Corporate setting.

Finally, you may have consumers of your analysis that would like to interact with the data themselves. For that select group, we will walk-through developing and deploying a Shiny App.

10.1 Markdown

10.2 Automate PowerPoint

Despite the popularity and growth of visualization tools such as Tableau, Power BI, DOMO, etc, there continues to be a need, certainly in the corporate world, for report delivery via Microsoft’s PowerPoint. PowerPoint still has some advantages over these newer report dissimentation portals; greater customization of output, no worries regarding audience ability to view, ease of forwarding via email, to name a few.

One of the disadanatges of PowerPoint however, is updating the charts, tables and text based on the latest data available. Yes, I am aware one can link to Excel and oher sources, but links have a way of breaking when you need them to work most. Here, I describe an approach taking advantage of the power of R to gather and organize data in the form of text, tables, and charts, then export that data to your favorite PowerPoint template, and finally, distribute your completed presentation using a Outlook - all this using R programming.

We’ll begin by loading our first of several packages, Quandl, which we’ll use to gather some economic data from the Federal Reserve for Economic Data (FRED).

Let’s now define a few variables to extract from FRED: GDP, Housing Starts, US/Euro FX, and Consumer Price Index.

library(Quandl)
gdp = head(Quandl("FRED/GDP"),8)
houst = head(Quandl("FRED/HOUST"),8)
fx = head(Quandl("FRED/EXUSEU"),8)
cpi = head(Quandl("FRED/CPIAUCSL"),8)

With our data retrieved, let’s load a couple more packages and build some charts. For this, we’ll use ggplot2 and ggthemes.

library(Quandl)
gdp = head(Quandl("FRED/GDP"),8)
houst = head(Quandl("FRED/HOUST"),8)
fx = head(Quandl("FRED/EXUSEU"),8)
cpi = head(Quandl("FRED/CPIAUCSL"),8)


library(ggplot2)
library(ggthemes)

####GDP
gdp_plot 
geom_bar(stat="identity", position=position_dodge(width = 1), colour="black") +
scale_fill_manual(values=c("#C0C0C0", "#87CEEB")) +
ggtitle("GDP Annual Rate") + 
theme_minimal() + 
geom_text(aes(label=Value),hjust=0.5, vjust=-.5, position=position_dodge(width = 1), 
size=2.5) + 
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
theme(legend.title=element_blank()) +
theme(axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank())

####Housing Starts
houst_plot 
geom_bar(stat="identity", position=position_dodge(width = 1), colour="black") +
scale_fill_manual(values=c("#C0C0C0", "#87CEEB")) +
ggtitle("Housing Starts") + 
theme_minimal() + 
geom_text(aes(label=Value),hjust=0.5, vjust=-.5, position=position_dodge(width = 1), 
size=2.5) + 
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
theme(legend.title=element_blank()) +
theme(axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank())

####USD/Euro
fx_plot 
geom_bar(stat="identity", position=position_dodge(width = 1), colour="black") +
scale_fill_manual(values=c("#C0C0C0", "#87CEEB")) +
ggtitle("USD/Euro") + 
theme_minimal() + 
geom_text(aes(label=Value),hjust=0.5, vjust=-.5, position=position_dodge(width = 1), 
size=2.5) + 
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
theme(legend.title=element_blank()) +
theme(axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank())

####Consumer Price Index
cpi_plot 
geom_bar(stat="identity", position=position_dodge(width = 1), colour="black") +
scale_fill_manual(values=c("#C0C0C0", "#87CEEB")) +
ggtitle("Consumer Price Index") + 
theme_minimal() + 
geom_text(aes(label=Value),hjust=0.5, vjust=-.5, position=position_dodge(width = 1), 
size=2.5) + 
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
theme(legend.title=element_blank()) +
theme(axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank())

To organize our charts in PowerPoint, we will use a Multiplot function, sourced from Peter Haschke.

library(grid)

numPlots = length(plots)

If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
Make the panel
ncol: Number of columns of plots
nrow: Number of rows needed, calculated from # of cols
layout 
ncol = cols, nrow = ceiling(numPlots/cols))
}

if (numPlots==1) {
print(plots[[1]])

} else {
Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

for (i in 1:numPlots) {

print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}

We are now ready to begin building the PowerPoint output. For this, we’ll use a few more packages: ReporteRs, ReporteRsjars, and magrittr.

Begin populating PowerPoint slides

library(ReporteRs)
library(ReporteRsjars)
library(magrittr)
options( "ReporteRs-fontsize" = 12 )
Create a FlexTable with data.frame Economy, display rownames
use different formatting properties for header and body cells
packs 
lapply(packs,require,character.only = TRUE)

Locate your favorite PowerPoint template to load your charts to.

options( "ReporteRs-fontsize" = 12 )

lapply(packs,require,character.only = TRUE)

Now, we can build some slides.

mydoc % 
addSlide( slide.layout = "Title Slide" ) %>% 
addTitle( "Economic Update" ) %>% 
addSubtitle(format(date))

####slide2: Use of Slides ------------------
options( "ReporteRs-fontsize" = 26 )
texts = c( "These slides provide history and forecast for key economic indicators..", 
"This is for presentation purposes only.")

mydoc % 
addSlide( slide.layout = "Title and Content" ) %>% 
addTitle( "Use of Slides" ) %>% 
addParagraph( value = texts )

####slide3: Placeholder Summary ------------------
mydoc % 
addSlide( slide.layout = "Title and Content" ) %>% 
addTitle( "Economic Summary" ) %>% 
addParagraph( value = texts )

####slide4: Economic Indidicators ------------------
mydoc % 
addSlide( slide.layout = "Title and Content" ) %>% 
addTitle( "Economic Indicators" ) %>% 
addPlot( function( ) print( multiplot(gdp_plot, houst_plot, fx_plot, cpi_plot, cols=2) )) %>% 
addFooter("Source: Federal Bank Reserve St. Louis")

####Let's write our new presentation as a new file.
writeDoc( mydoc, file = '~/econ_update.pptx' )

With our report completed, let’s use the RDCOMClient package to distribute using Microsoft Outlook.

library(RDCOMClient)

OutApp 
outMail = OutApp$CreateItem(0)
outMail[["BCC"]] = 'recipient@email.com'
outMail[["subject"]] = "Economic Update"
outMail[["body"]] = "Colleagues, Please find attached the latest Report"
outMail[["Attachments"]]$Add('~/econ_update.pptx')

outMail$Send()

And that’s it. To recap, we:

  • Retrieved data from FRED
  • Built some charts
  • Placed those charts and some text to a PowerPoint template
  • Distributed the final report via Outlook = Further, one could automate this procedure using the taskscheduleR, package.

10.3 Create a Desktop Application

Introduction

Not every company may have the resources , read money or expertise, to launch a web-based analytics platform. Also, perhaps you are in the early stages of determining if an online analytics portal, such as Tableau, PowerBI, DOMO, etc, provide, or there is a very specific analysis, for just 2-3 people to review and investing in a larger platform can not be justified. A solution may be creating and deploying a desktop application with R Shiny. Before I proceed further, I should give credit where credit is due. I could not have created the Desktop Economic Dashboard without the insights from Lee Pang’s post, ’Deploying Desktop Apps with R“, nor without the walk-through guidance of Dashboard development from the folks at R Studio.

Admittedly, what I am providing here is nothing particularly new, but my goal in providing these steps is that it will show how, without much effort and zero cost, one may create an economic dashboard for your business or personal investment needs. I make no claims as to the accuracy of the forecasts and this is for demonstration purposes only. The data will be retrieved from Federal Reserve for Economic Data (FRED) using the R quantmod package. We will then use that data to create an arima forecast using the R forecast package. To view the data, we’ll use dygraphs package. Finally, we’ll wrap those charts in a Shiny Dashboard and deploy using a desktop app.

####Load Packages 
library(shiny)
library(shinydashboard)
library(quantmod)
library(forecast)
library(dygraphs)
library(rpivotTable)

####Define Key Dates
r1start <-  
r1end <- 
r2start <-  
r2end <-  
date.start <-  
date.end <-  
date.end2 <- 

Retrieve Data Now, we will retrieve some data key economic data from FRED. I have identified 17 variables I would like to use in the dashboard. For ease, I extract the dates I want using the date identifiers listed above, and also rename the variables A->Q.

Datatickers <- getSymbols(tickers
, src = "FRED" # needed!
, from = date.start # ignored
, to = date.end # ignored
, env = data
, adjust = TRUE
)

Develop Forecast For each variable I create a basic arima model. For this dashboard, I want to create a 5 year forecast; So, depending on how the variables are naturally aggregated, I set the n.ahead to the appropriate value using the date.end2 defined in key dates above.

Group Data For the employment data, I would like a single chart that shows the white collar workers by type. I was unable to locate an official definition of white collar workers, so I created my own.

I would also like to create a pivot table which will be on a separate tab as the charts. For this, I’ll create a data frame of selected variables.

User Interface Finally, I’m ready to actually build a dashboard. I’ll begin by scripting the ui. I’ll name the dashboard a very creative name, “Economic Dashboard”. There will be two menu items in the dashboard, ‘Economy’, which will hold the charts, and ‘Pivot’, which will allow one to view the data in various tables and charts.

I can now create the body portion of the dashboard pages. First the charts.

I’ll create 11 additional boxes to hold the remaining data sets, with the last one being the WCW data set mentioned above.

The Pivot table is straightforward and will not require a server function in our basic example.

Build Server Actions

Now for the server side. The following is an example of the first dygraph which will show GDP. I’ll also create 11 more dygraphs, each with the group ‘economy’, so when dates are selected for one, all charts move in sync.

Finally, I’ll end with a script to close the app when the browser is closed. This is important, otherwise the script will continue running in the background and frustrate users when they want to launch a second time.

The above is held in a single file named app.R. You can run this app locally and it will retrieve the latest economic data from the Federal Reserve and create a basic arima forecast model 5 years out. But we also want to allow others to use this excellent app we created and for that we’ll need to download some additional tools. Here, I won’t rehash Lee Pang’s post, ‘Deploying Desktop Apps with R’ . But, in brief you will need to download R-Portable and Google Chrome Portable and save them to a common folder you create.

I created a common folder named ‘RDash’. With a sub-folder for Google Chrome Portable, a subfolder for R-Portable and a third for shiny that holds the app.r file.

The DASH shortcut is for the end-user to place on their desktop when they want to run the Dashboard. This icon file is nothing more than an icon I found somewhere that I’m using for the Shortcut. The ‘run’ script is a vb script that calls the runShinyApp file. The ’run vb script contains:

Note that I placed the folder in my C drive. If you place somewhere else, you’ll need to change the run and runShinyApp scripts accordingly.

Final Thoughts Retrieving data directly from the Federal Reserve using quantmod, building a basic dashboard using Shiny Dashboards, embedding that dashboard with synchronized dygraphs and a pivot chart were the beginning. Making it available to other users as a desktop application allows greater use and appreciation for the power of R.

There is undoubtedly many areas for improvement with this dashboard, from layout to the forecasting model applied. I hope you’ll take this as I have, as a first step toward doing more with R.

10.4 Review