<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Shiny on R Views</title>
    <link>https://rviews.rstudio.com/tags/shiny/</link>
    <description>Recent content in Shiny on R Views</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Wed, 20 Jul 2022 00:00:00 +0000</lastBuildDate>
    <atom:link href="https://rviews.rstudio.com/tags/shiny/" rel="self" type="application/rss+xml" />
    
    
    
    
    <item>
      <title>Shiny showcase at rstudio::conf(2022)</title>
      <link>https://rviews.rstudio.com/2022/07/20/shiny-showcase-at-rstudio-conf-2022/</link>
      <pubDate>Wed, 20 Jul 2022 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2022/07/20/shiny-showcase-at-rstudio-conf-2022/</guid>
      <description>
        

&lt;p&gt;&lt;img src=&#34;shiny2.png&#34; height = &#34;500&#34; width=&#34;100%&#34; alt=&#34;rstudio::conf Shiny Talks Schedule&#34;&gt;&lt;/p&gt;

&lt;p&gt;Beginning with the invitation-only 2016 &lt;a href=&#34;https://www.rstudio.com/resources/shiny-dev-con-2016/&#34;&gt;Shiny Developer Conference&lt;/a&gt;, &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;Shiny&lt;/a&gt; has played a prominent part in all RStudio conferences, and &lt;a href=&#34;https://www.rstudio.com/conference/&#34;&gt;rstudio::conf(2022)&lt;/a&gt; is no exception. Two workshops and eighteen talks showcase Shiny&amp;rsquo;s multiple, ever-increasing capabilities. What started out as a way to introduce R&amp;rsquo;s interactive statistical computations to the web has grown into a production-grade tool that supports serious data science workflows and facilitates the communication of data-generated insights throughout large organizations in both industry and government.&lt;/p&gt;

&lt;p&gt;Here is your Shiny guide to rstudio::conf(2022). But before you attend the show or see the movie, you may want to have a look at the &lt;a href=&#34;https://mastering-shiny.org/&#34;&gt;book&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Keynotes and talks will be livestreamed on the &lt;a href=&#34;https://www.rstudio.com/conference/&#34;&gt;rstudio::conf(2022) website&lt;/a&gt;, free and open to all. No registration is required. If you would like, you can sign up to get access to our Discord server to meet and chat with attendees during conf.&lt;/p&gt;

&lt;p&gt;On July 27-28th, head to the conference website to watch the livestreams and ask questions alongside other attendees.&lt;/p&gt;

&lt;h3 id=&#34;keynotes&#34;&gt;Keynotes&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/keynotes/past-future-shiny/&#34;&gt;The Past and Future of Shiny&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&#34;workshops&#34;&gt;Workshops&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://shinyprod.com/&#34;&gt;Building Production-Quality Shiny Applications&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://rstudio-conf-2022.github.io/get-started-shiny/&#34;&gt;Getting Started with Shiny&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&#34;talks&#34;&gt;Talks&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/r-shiny-conception-to-cloud/&#34;&gt;R Shiny - From Conception to the Cloud&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/optimal-allocation-of-covid-19/&#34;&gt;Optimal allocation of COVID-19 vaccines in West Africa - A Shiny success story&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/r-markdown-rstudio-connect-r/&#34;&gt;R Markdown + RStudio Connect + R Shiny: A Recipe for Automated Data Processing, Error Logging, and Process Monitoring&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/made-entire-e-commerce-platform/&#34;&gt;I made an entire e-commerce platform on Shiny&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/let-mobile-shine-leveraging-css/&#34;&gt;Let your mobile shine - Leveraging CSS concepts to make shiny apps mobile responsive&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/shinyslack-connecting-slack-teams/&#34;&gt;{shinyslack}: Connecting Slack Teams to Shiny Apps&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/leafdown-interactive-multi-layer-maps/&#34;&gt;leafdown: Interactive multi-layer maps in Shiny apps&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/say-hello-to-multilingual-shiny/&#34;&gt;Say Hello! to Multilingual Shiny Apps&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/cross-industry-anomaly-detection-solutions/&#34;&gt;Cross-Industry Anomaly Detection Solutions with R and Shiny&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/running-shiny-without-server/&#34;&gt;Running Shiny without a server&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/new-way-to-build-shiny/&#34;&gt;A new way to build your Shiny app&amp;rsquo;s UI&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/creating-design-system-for-shiny/&#34;&gt;Creating a Design System for Shiny and RMarkdown&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/shiny-dashboards-for-biomedical-research/&#34;&gt;Shiny Dashboards for Biomedical Research Funding&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/dashboard-builder/&#34;&gt;Dashboard-Builder: Building Shiny Apps without writing any code&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/introducing-rhino-shiny-application-framework/&#34;&gt;Introducing Rhino: Shiny application framework for enterprise&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/robust-framework-for-automated-shiny/&#34;&gt;A Robust Framework for Automated Shiny App Testing&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://www.rstudio.com/conference/2022/talks/shinytest2-unit-testing-for-shiny/&#34;&gt;{shinytest2}: Unit testing for Shiny applications&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2022/07/20/shiny-showcase-at-rstudio-conf-2022/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>A beginner&#39;s guide to Shiny modules</title>
      <link>https://rviews.rstudio.com/2021/10/20/a-beginner-s-guide-to-shiny-modules/</link>
      <pubDate>Wed, 20 Oct 2021 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2021/10/20/a-beginner-s-guide-to-shiny-modules/</guid>
      <description>
        
&lt;script src=&#34;/2021/10/20/a-beginner-s-guide-to-shiny-modules/index_files/header-attrs/header-attrs.js&#34;&gt;&lt;/script&gt;


&lt;p&gt;&lt;em&gt;This post by Emily Riederer is the winning entry in our recent &lt;a href=&#34;https://rviews.rstudio.com/2021/08/04/r-views-blog-contest/&#34;&gt;Call for Documentation&lt;/a&gt; contest. Emily is a Senior Analytics Manager at Capital One where she leads a team building internal analytical tools including R packages, datamarts, and Shiny apps. Outside of work, Emily can be found sharing more code and ideas about analytics on her &lt;a href=&#34;https://emilyriederer.netlify.com/&#34;&gt;website&lt;/a&gt;, Twitter (&lt;span class=&#34;citation&#34;&gt;@emilyriederer&lt;/span&gt;) and GitHub (&lt;span class=&#34;citation&#34;&gt;@emilyriederer&lt;/span&gt;).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Shiny modules are often taught as an advanced topic, but they can also be a great way for novice Shiny developers to start building more complex applications. If you already are an R user who likes to &lt;strong&gt;think and write functions&lt;/strong&gt; and &lt;strong&gt;understand Shiny basics&lt;/strong&gt; (i.e. reactivity), then modules &lt;strong&gt;for certain types of tasks&lt;/strong&gt; (discussed at the end of this post) are an excellent way to up your game.&lt;/p&gt;
&lt;p&gt;Shiny’s tendency toward monolithic scripts and &lt;em&gt;lack&lt;/em&gt; of function-based thinking in introductory materials felt so unlike normal R programming. So, not only is it &lt;em&gt;possible&lt;/em&gt; to learn modules early, it may actually be decidedly easier than the alternative depending on your frame of mind.&lt;/p&gt;
&lt;p&gt;In this post, I walk through a toy example of building a reporting app from the &lt;code&gt;flights&lt;/code&gt; data in the &lt;a href=&#34;https://cran.r-project.org/package=nycflights13&#34;&gt;nycflights13&lt;/a&gt; package to demonstrate how modules help scale basic Shiny skills.&lt;/p&gt;
&lt;div id=&#34;why-modules&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Why Modules?&lt;/h2&gt;
&lt;p&gt;Modules act like functions by wrapping up sets of Shiny UI and server elements. You may wonder why you cannot just accomplish this with the normal R functions. The reason for this is a bit technical and is explained well in &lt;em&gt;Mastering Shiny&lt;/em&gt;. However, the technical knowledge needed to understand “why functions don’t work” should not make modules an advanced topic. If you see the value of writing functions, you are more than ready to take advantage of modules in app development.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;motivating-example&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Motivating Example&lt;/h2&gt;
&lt;p&gt;For the sake of argument, let’s pretend that we are building an airline dashboard to track travel delays against established thresholds. We have the following requirements:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Let users pick a month of interest to visualize&lt;/li&gt;
&lt;li&gt;For each metric of interest, users should be able to:
&lt;ul&gt;
&lt;li&gt;See a time-series plot of the average daily value of the metric&lt;/li&gt;
&lt;li&gt;Download a PNG of the plot&lt;/li&gt;
&lt;li&gt;Read a text summary of how often the value breached the threshold&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;The metrics of interest are:
&lt;ul&gt;
&lt;li&gt;Average departure delay&lt;/li&gt;
&lt;li&gt;Average arrival delay&lt;/li&gt;
&lt;li&gt;Proportion of daily flights with an arrival delay exceeding 5 minutes&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Below is a preview of the final application. The full app is currently hosted in &lt;a href=&#34;https://emilyriederer.shinyapps.io/shiny-modules-demo/&#34;&gt;ShinyApps.io&lt;/a&gt; and the code available &lt;a href=&#34;https://github.com/emilyriederer/demo-shiny-modules&#34;&gt;on GitHub&lt;/a&gt;. It would not win any beauty contests, but its simple style allows us to focus on modules in the code.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://github.com/emilyriederer/docs-submission/blob/master/shiny-modules/app-photo.PNG?raw=true&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Two line graphs for departure and arrival times where we see variation compared to the average&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;set-up&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Set-Up&lt;/h2&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(shiny)
library(nycflights13)
library(dplyr)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Attaching package: &amp;#39;dplyr&amp;#39;&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## The following objects are masked from &amp;#39;package:stats&amp;#39;:
## 
##     filter, lag&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## The following objects are masked from &amp;#39;package:base&amp;#39;:
## 
##     intersect, setdiff, setequal, union&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To understand the following explanation, it helps to familiarize yourself with the data. We filter the &lt;code&gt;flights&lt;/code&gt; data down to a single airline and aggregate the results by day.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ua_data &amp;lt;-
  nycflights13::flights %&amp;gt;%
  filter(carrier == &amp;quot;UA&amp;quot;) %&amp;gt;%
  mutate(ind_arr_delay = (arr_delay &amp;gt; 5)) %&amp;gt;%
  group_by(year, month, day) %&amp;gt;%
  summarize(
    n = n(),
    across(ends_with(&amp;quot;delay&amp;quot;), mean, na.rm = TRUE)
    ) %&amp;gt;%
  ungroup()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## `summarise()` has grouped output by &amp;#39;year&amp;#39;, &amp;#39;month&amp;#39;. You can override using the `.groups` argument.&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(ua_data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 6 x 7
##    year month   day     n dep_delay arr_delay ind_arr_delay
##   &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt;     &amp;lt;dbl&amp;gt;     &amp;lt;dbl&amp;gt;         &amp;lt;dbl&amp;gt;
## 1  2013     1     1   165      7.65     6.27          0.476
## 2  2013     1     2   170     12.8      7.04          0.458
## 3  2013     1     3   159      8.66    -2.76          0.357
## 4  2013     1     4   161      6.84    -9.86          0.180
## 5  2013     1     5   117      9.66     0.786         0.274
## 6  2013     1     6   137      9.79     3.53          0.409&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we define the plotting function that we will use to visualize a month-long timeseries of data for each metric.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;viz_monthly &amp;lt;- function(df, y_var, threshhold = NULL) {
  
  ggplot(df) +
    aes(
      x = .data[[&amp;quot;day&amp;quot;]],
      y = .data[[y_var]]
    ) +
    geom_line() +
    geom_hline(yintercept = threshhold, color = &amp;quot;red&amp;quot;, linetype = 2) +
    scale_x_continuous(breaks = seq(1, 29, by = 7)) +
    theme_minimal()
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For example, to visualize the average arrival delay by day for all of March and compare it to a threshold of 10 minutes, we can write:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ua_data %&amp;gt;%
  filter(month == 3) %&amp;gt;%
  viz_monthly(&amp;quot;arr_delay&amp;quot;, threshhold = 10)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/2021/10/20/a-beginner-s-guide-to-shiny-modules/index_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;one-module-at-a-time&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;One Module at a Time&lt;/h2&gt;
&lt;p&gt;Modules don’t just help organize your code; they help you organize your &lt;em&gt;thinking&lt;/em&gt;. Given our app requirements, it might feel overwhelming where to start. Filtering the data? Making the plots? Wiring up buttons? Inevitably, when juggling many components, you’re likely to introduce a bug by copy-pasting a line with the wrong &lt;code&gt;id&lt;/code&gt; or getting nested parentheses out of whack.&lt;/p&gt;
&lt;p&gt;Instead, modules essentially allow your to write &lt;em&gt;many simple Shiny apps&lt;/em&gt; and compose them together.&lt;/p&gt;
&lt;p&gt;For example, we might decide that first we just want to focus on a very simple app: given a monthly subset of the data, a metric, and a threshold of interest. Let’s write a simple text summary of the flights performance. We now know we just need to define a UI (&lt;code&gt;text_ui&lt;/code&gt;) with a single call to &lt;code&gt;textOutput()&lt;/code&gt;, a server (&lt;code&gt;text_server&lt;/code&gt;) that does a single calculation and calls &lt;code&gt;renderText()&lt;/code&gt;. Best of all, we can immediately see whether or not our “app” works by writing a minimalist testing function (&lt;code&gt;text_demo&lt;/code&gt;) which renders the text for a small, fake dataset.&lt;/p&gt;
&lt;p&gt;Those steps are implemented in a file called &lt;code&gt;mod-text.R&lt;/code&gt;:&lt;/p&gt;
&lt;p&gt;You can find all of the code for this tutorial in this &lt;a href=&#34;https://github.com/emilyriederer/demo-shiny-modules&#34;&gt;demo Shiny application&lt;/a&gt; repository.
We can follow the same pattern to create a module for the plot itself (in the file &lt;a href=&#34;https://github.com/emilyriederer/demo-shiny-modules/blob/master/mod-plot.R&#34;&gt;&lt;code&gt;mod-plot.R&lt;/code&gt;&lt;/a&gt;) consisting of a UI (&lt;code&gt;plot_ui&lt;/code&gt;), a server (&lt;code&gt;plot_server&lt;/code&gt;), and a testing function (&lt;code&gt;plot_demo&lt;/code&gt;). This module is responsible for plotting one metric and allowing users to download the results.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;composing-modules&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Composing Modules&lt;/h2&gt;
&lt;p&gt;We now have a text module and a plot module. However, for each metric of interest, we want to produce &lt;em&gt;both&lt;/em&gt;. We could call these two modules one-at-a-time, but we can also compose multiple modules together so that we can produce in single commands everything that we need for a given metric.&lt;/p&gt;
&lt;p&gt;With all of the underlying plot and text module logic abstracted, our metric module definition (in the &lt;code&gt;mod-metr.R&lt;/code&gt; file) is very clean and simple:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# metric module ----
metric_ui &amp;lt;- function(id) {
  
  fluidRow(
    text_ui(NS(id, &amp;quot;metric&amp;quot;)),
    plot_ui(NS(id, &amp;quot;metric&amp;quot;))
  )
  
}
metric_server &amp;lt;- function(id, df, vbl, threshhold) {
  
  moduleServer(id, function(input, output, session) {
    
    text_server(&amp;quot;metric&amp;quot;, df, vbl, threshhold)
    plot_server(&amp;quot;metric&amp;quot;, df, vbl, threshhold)
    
  })
  
}
metric_demo &amp;lt;- function() {
  
  df &amp;lt;- data.frame(day = 1:30, arr_delay = 1:30)
  ui &amp;lt;- fluidPage(metric_ui(&amp;quot;x&amp;quot;))
  server &amp;lt;- function(input, output, session) {
    metric_server(&amp;quot;x&amp;quot;, reactive({df}), &amp;quot;arr_delay&amp;quot;, 15)
  }
  shinyApp(ui, server)
  
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, we can test that these components went together as we intended by running the &lt;code&gt;metric_demo()&lt;/code&gt; function. We see the text from our text module on top of the plot and button from our plot module:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://github.com/emilyriederer/docs-submission/blob/master/shiny-modules/mod-demo.PNG?raw=true&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Line graph for flight arrival times where we see how many days exceeded the average&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;This may be overkill for a simple app, but composing modules is very useful as your application grows in complexity. Everything you bundle into a module gives you a license to forget about how the next layer lower is implemented and frees up your mind to take on the next challenge.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;putting-it-all-together&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Putting it all together&lt;/h2&gt;
&lt;p&gt;Finally, we are ready to write our complete application in a file called &lt;code&gt;flights-app.R&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;viz_monthly &amp;lt;- function(df, y_var, threshhold = NULL) {
  
  ggplot(df) +
    aes(
      x = .data[[&amp;quot;day&amp;quot;]],
      y = .data[[y_var]]
    ) +
    geom_line() +
    geom_hline(yintercept = threshhold, color = &amp;quot;red&amp;quot;, linetype = 2) +
    scale_x_continuous(breaks = seq(1, 29, by = 7)) +
    theme_minimal()
}

# text module ----
text_ui &amp;lt;- function(id) {
  
  fluidRow(
    textOutput(NS(id, &amp;quot;text&amp;quot;))
  )
  
}

text_server &amp;lt;- function(id, df, vbl, threshhold) {
  
  moduleServer(id, function(input, output, session) {
    
    n &amp;lt;- reactive({sum(df()[[vbl]] &amp;gt; threshhold)})
    output$text &amp;lt;- renderText({
      paste(&amp;quot;In this month&amp;quot;, 
            vbl, 
            &amp;quot;exceeded the average daily threshhold of&amp;quot;,
            threshhold,
            &amp;quot;a total of&amp;quot;, 
            n(), 
            &amp;quot;days&amp;quot;)
    })
    
  })
  
}

text_demo &amp;lt;- function() {
  
  df &amp;lt;- data.frame(day = 1:30, arr_delay = 1:30)
  ui &amp;lt;- fluidPage(text_ui(&amp;quot;x&amp;quot;))
  server &amp;lt;- function(input, output, session) {
    text_server(&amp;quot;x&amp;quot;, reactive({df}), &amp;quot;arr_delay&amp;quot;, 15)
  }
  shinyApp(ui, server)
}
  
# plot module ----
plot_ui &amp;lt;- function(id) {
  
  fluidRow(
    column(11, plotOutput(NS(id, &amp;quot;plot&amp;quot;))),
    column( 1, downloadButton(NS(id, &amp;quot;dnld&amp;quot;), label = &amp;quot;&amp;quot;))
  )
  
}

plot_server &amp;lt;- function(id, df, vbl, threshhold = NULL) {
  
  moduleServer(id, function(input, output, session) {
    
    plot &amp;lt;- reactive({viz_monthly(df(), vbl, threshhold)})
    output$plot &amp;lt;- renderPlot({plot()})
    output$dnld &amp;lt;- downloadHandler(
      filename = function() {paste0(vbl, &amp;#39;.png&amp;#39;)},
      content = function(file) {ggsave(file, plot())}
    )
    
  })
}

plot_demo &amp;lt;- function() {
  
  df &amp;lt;- data.frame(day = 1:30, arr_delay = 1:30)
  ui &amp;lt;- fluidPage(plot_ui(&amp;quot;x&amp;quot;))
  server &amp;lt;- function(input, output, session) {
    plot_server(&amp;quot;x&amp;quot;, reactive({df}), &amp;quot;arr_delay&amp;quot;)
  }
  shinyApp(ui, server)
}

# metric module ----
metric_ui &amp;lt;- function(id) {
  
  fluidRow(
    text_ui(NS(id, &amp;quot;metric&amp;quot;)),
    plot_ui(NS(id, &amp;quot;metric&amp;quot;))
  )
  
}

metric_server &amp;lt;- function(id, df, vbl, threshhold) {
  
  moduleServer(id, function(input, output, session) {
    
    text_server(&amp;quot;metric&amp;quot;, df, vbl, threshhold)
    plot_server(&amp;quot;metric&amp;quot;, df, vbl, threshhold)
    
  })
  
}

metric_demo &amp;lt;- function() {
  
  df &amp;lt;- data.frame(day = 1:30, arr_delay = 1:30)
  ui &amp;lt;- fluidPage(metric_ui(&amp;quot;x&amp;quot;))
  server &amp;lt;- function(input, output, session) {
    metric_server(&amp;quot;x&amp;quot;, reactive({df}), &amp;quot;arr_delay&amp;quot;, 15)
  }
  shinyApp(ui, server)
  
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load libraries ----
library(nycflights13)
library(shiny)
library(ggplot2)
library(dplyr)
# data prep ----
ua_data &amp;lt;-
  nycflights13::flights %&amp;gt;%
  filter(carrier == &amp;quot;UA&amp;quot;) %&amp;gt;%
  mutate(ind_arr_delay = (arr_delay &amp;gt; 5)) %&amp;gt;%
  group_by(year, month, day) %&amp;gt;%
  summarize(
    n = n(),
    across(ends_with(&amp;quot;delay&amp;quot;), mean, na.rm = TRUE)
    ) %&amp;gt;%
  ungroup()
# full application ----
ui &amp;lt;- fluidPage(
  
  titlePanel(&amp;quot;Flight Delay Report&amp;quot;),
  
  sidebarLayout(
  sidebarPanel = sidebarPanel(
    selectInput(&amp;quot;month&amp;quot;, &amp;quot;Month&amp;quot;, 
                choices = setNames(1:12, month.abb),
                selected = 1
    )
  ),
  mainPanel = mainPanel(
    h2(textOutput(&amp;quot;title&amp;quot;)),
    h3(&amp;quot;Average Departure Delay&amp;quot;),
    metric_ui(&amp;quot;dep_delay&amp;quot;),
    h3(&amp;quot;Average Arrival Delay&amp;quot;),
    metric_ui(&amp;quot;arr_delay&amp;quot;),
    h3(&amp;quot;Proportion Flights with &amp;gt;5 Min Arrival Delay&amp;quot;),
    metric_ui(&amp;quot;ind_arr_delay&amp;quot;)
  )
)
)
server &amp;lt;- function(input, output, session) {
  
  output$title &amp;lt;- renderText({paste(month.abb[as.integer(input$month)], &amp;quot;Report&amp;quot;)})
  df_month &amp;lt;- reactive({filter(ua_data, month == input$month)})
  metric_server(&amp;quot;dep_delay&amp;quot;, df_month, vbl = &amp;quot;dep_delay&amp;quot;, threshhold = 10)
  metric_server(&amp;quot;arr_delay&amp;quot;, df_month, vbl = &amp;quot;arr_delay&amp;quot;, threshhold = 10)
  metric_server(&amp;quot;ind_arr_delay&amp;quot;, df_month, vbl = &amp;quot;ind_arr_delay&amp;quot;, threshhold = 0.5)
  
}
shinyApp(ui, server)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can find all of the code for this tutorial in this &lt;a href=&#34;https://github.com/emilyriederer/demo-shiny-modules&#34;&gt;demo Shiny application&lt;/a&gt; repository.&lt;/p&gt;
&lt;p&gt;Notice how few lines of code this file requires to create all of our components and interactions! We’ve eliminated much of the dense code, nesting, and potential duplication we might have encountered if trying to write our application without modules. The top-level code is accessible, semantic, and declarative. It is easy to understand the intent of each line and which pieces of UI and server logic are responsible for which components.&lt;/p&gt;
&lt;p&gt;Not all modules are made alike, and in this walk-through I chose simple tasks to demonstrate. Note that our modules &lt;em&gt;consume&lt;/em&gt; a reactive variable (data) from the environment, but they do not attempt to &lt;em&gt;alter&lt;/em&gt; the global environment or &lt;em&gt;exchange&lt;/em&gt; information between them. Modules that simply consume reactives are the easiest way to start out.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note from the Editor: Emily’s winning entry displays several characteristics of good technical writing. She is laser focused on her audience: R users who have some Shiny experience but who are not familiar with modules. Emily’s prose is direct, simple, informal and engaging. Reading it, I feel as if Emily is beside me showing me how things work, and that she cares about me understanding it. Emily’s code is spacious, and laid out to be read by others. And maybe not so obvious on the first reading, Emily’s writing is disciplined. It is clear that she knows a lot more about things than she has has put into the post, but is working under self imposed constraints in pursuit of clarity.&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2021/10/20/a-beginner-s-guide-to-shiny-modules/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>A Custom Forest Plot from Wonderful Wednesdays</title>
      <link>https://rviews.rstudio.com/2021/01/15/wonderful-wednesdays-forest-plot/</link>
      <pubDate>Fri, 15 Jan 2021 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2021/01/15/wonderful-wednesdays-forest-plot/</guid>
      <description>
        

&lt;p&gt;&lt;em&gt;Waseem Medhat is a Statistical Programmer and Computational Experimentalist who resides in Alexandria, Egypt&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This post takes a closer look at the forest plot that was mentioned in a &lt;a href=&#34;https://rviews.rstudio.com/2021/01/11/wonderful-wednesdays/&#34;&gt;previous post&lt;/a&gt; introducing PSI&amp;rsquo;s Wonderful Wednesdays events. It describes a custom version of a forest plot with additional bands to visualize heterogeneity between studies in a meta-analysis that was part of a project submitted to the Wonderful Wednesdays challenge hosted by PSI and reviewed by statisticians in the organization. Find more information
&lt;a href=&#34;https://vis-sig.github.io/blog/posts/2020-12-03-wonderful-wednesdays-december-2020/&#34;&gt;here&lt;/a&gt;. The plot is built with JavaScript using the
&lt;a href=&#34;https://d3js.org/&#34;&gt;D3.js&lt;/a&gt; library and wrapped in a
&lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;Shiny&lt;/a&gt; app with the help of the
&lt;a href=&#34;https://rstudio.github.io/r2d3/&#34;&gt;R2D3&lt;/a&gt; package.&lt;/p&gt;

&lt;h2 id=&#34;background-problem&#34;&gt;Background problem&lt;/h2&gt;

&lt;p&gt;The problem around this visualization is specific to meta-analysis, which is the statistical pooling of the results of multiple studies (e.g. a multi-center clinical trial) to obtain a single, more powerful estimate. The choice of pooling model (fixed effect vs. random effects) depends on the heterogeneity of effect size between studies. So, the main question that I wanted to answer with this visualization is:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&amp;ldquo;What graphical tools can be used to assess heterogeneity?&amp;rdquo;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Like any statistical graphic, the purpose of the visualization is to complement the statistical measures of heterogeneity, like I^2^, to give a more complete picture.&lt;/p&gt;

&lt;h2 id=&#34;plot-description&#34;&gt;Plot description&lt;/h2&gt;

&lt;p&gt;&lt;img src=&#34;https://waseem-medhat.netlify.app/post/forest-plot-with-heterogeneity-bands_files/forest_plot_with_bands.png&#34; alt=&#34;&#34; /&gt;&lt;/p&gt;

&lt;p&gt;A lot of the plot components are directly comparable to the typical &lt;a href=&#34;https://en.wikipedia.org/wiki/Forest_plot&#34;&gt;forest
plot&lt;/a&gt;, which is very popular in the medical field as visualization tool in meta-analyses. Its main features are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A square for each point estimate for a study. The square size is proportional
to the sample size (i.e. weight) of that study.&lt;/li&gt;
&lt;li&gt;A line for each confidence interval of the effect size in a study.&lt;/li&gt;
&lt;li&gt;Diamonds that represent the pooled estimate using either fixed-effect or random-effects model. The diamond width represents the confidence interval around the pooled estimate.&lt;/li&gt;
&lt;li&gt;The plot is usually combined with a tabular display of the numbers represented by the plot.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;My own additions are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Colored bands to give a better visualization of the heterogeneity between studies. There is a band for each study, with a width equal to its confidence interval. All the bands are semi-transparent and overlayed over each other so that more overlapping produces darker areas.&lt;/li&gt;
&lt;li&gt;More attention to annotations than the typical plots, providing a title and a subtitle with the interventions and the outcome, respectively. Another label is also added to show which direction represents the &amp;ldquo;positive&amp;rdquo; effect.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&#34;shiny-app-description&#34;&gt;Shiny app description&lt;/h2&gt;

&lt;p&gt;&lt;img src=&#34;https://waseem-medhat.netlify.app/post/forest-plot-with-heterogeneity-bands_files/forest_plot_with_bands_shiny.png&#34; alt=&#34;&#34; /&gt;&lt;/p&gt;

&lt;p&gt;As a proof of concept for a viable product, I wrapped the plot in a Shiny app which provides additional interactive features:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Selection of summary measure, which can be expanded to include more than the
odds ratio and risk ratio.&lt;/li&gt;
&lt;li&gt;Control over the plot dimensions. Giving this control to the user allows the  plot to be conveniently visible in different screen sizes and deliverable forms (e.g.  a report or a dashboard).&lt;/li&gt;
&lt;li&gt;Help button that shows a guide for interpretation. This makes the information available on-demand instead having it a separate tab.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&#34;technologies-and-packages&#34;&gt;Technologies and packages&lt;/h2&gt;

&lt;h3 id=&#34;d3-js-javascript&#34;&gt;D3.js (JavaScript)&lt;/h3&gt;

&lt;p&gt;The plot itself (and associated tabular display) was built using D3.  Being a JavaScript library, D3 works with web technologies: HTML, CSS, and especially SVG. It has a lot of low-level tools that bind data to SVG shapes and change the shape properties accordingly. One particular advantage of using web technologies in this visualization is that CSS allows semi-transparent elements to &amp;ldquo;blend&amp;rdquo; colors in multiple ways, which allowed me to choose a blend mode that emphasizes the overlap.&lt;/p&gt;

&lt;h3 id=&#34;r2d3&#34;&gt;R2D3&lt;/h3&gt;

&lt;p&gt;R2D3 was the main wrapper around the D3 visualization. Beside the obvious
advantage of introducing an interface between R and D3 and allowing its
rendering in Shiny, it makes some steps easier like giving the data to the plot and making the plot take as much space as possible inside its container. Because of this, initial variables like &lt;code&gt;data&lt;/code&gt;, &lt;code&gt;width&lt;/code&gt;, &lt;code&gt;height&lt;/code&gt;, and (the container) &lt;code&gt;svg&lt;/code&gt; are provided by R2D3 and are not declared in the JavaScript code.&lt;/p&gt;

&lt;h3 id=&#34;shiny&#34;&gt;Shiny&lt;/h3&gt;

&lt;p&gt;It does not need an introduction at this point: Shiny is the de facto standard for R-based web applications. With the R2D3 package, I have available &lt;code&gt;d3Output()&lt;/code&gt; and &lt;code&gt;renderD3()&lt;/code&gt; to render the D3 plot just like any typical output in Shiny. Other Shiny packages I used are
&lt;a href=&#34;https://github.com/cwthom/shinyhelper&#34;&gt;shinyhelper&lt;/a&gt;, which provides a help button and rich modal dialogs for help content, and &lt;a href=&#34;http://rstudio.github.io/shinythemes/&#34;&gt;shinythemes&lt;/a&gt; to change the appearance of the app.&lt;/p&gt;

&lt;p&gt;By wrapping the visualization in a Shiny app, this project became a prototype that can be taken in a lot of different directions to include more effect sizes and other meta-analysis techniques, or maybe even add another module that imports the data, performs the meta-analysis, and send the results to this module to be visualized.&lt;/p&gt;

&lt;h2 id=&#34;links&#34;&gt;Links&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Live version of the Shiny app: &lt;a href=&#34;https://waseem-medhat.shinyapps.io/forest_plot_with_bands/&#34;&gt;https://waseem-medhat.shinyapps.io/forest_plot_with_bands/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href=&#34;https://github.com/waseem-medhat/forest_plot_with_bands&#34;&gt;https://github.com/waseem-medhat/forest_plot_with_bands&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Wonderful Wednesdays December submissions: &lt;a href=&#34;https://vis-sig.github.io/blog/posts/2020-12-03-wonderful-wednesdays-december-2020/&#34;&gt;https://vis-sig.github.io/blog/posts/2020-12-03-wonderful-wednesdays-december-2020/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2021/01/15/wonderful-wednesdays-forest-plot/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Crowd Counting Consortium Crowd Data and Shiny Dashboard</title>
      <link>https://rviews.rstudio.com/2020/08/31/crowd-counting-consortium-crowd-data-and-shiny-dashboard/</link>
      <pubDate>Mon, 31 Aug 2020 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2020/08/31/crowd-counting-consortium-crowd-data-and-shiny-dashboard/</guid>
      <description>
        


&lt;p&gt;&lt;em&gt;Jay Ulfelder, PhD, serves as Program Manager for the Nonviolent Action Lab, part of the Carr Center for Human Rights Policy at the Harvard Kennedy School. He has used R to work at the intersection of social science and data science for nearly two decades.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Where are people in the United States protesting in 2020, and what are they protesting about? How large have those crowds been? How many protesters have been arrested or injured? And how does this year’s groundswell of protest activity compare to the past several years, which had already produced some of the &lt;a href=&#34;https://www.washingtonpost.com/news/monkey-cage/wp/2017/02/07/this-is-what-we-learned-by-counting-the-womens-marches/&#34;&gt;largest single-day gatherings in U.S. history&lt;/a&gt;?&lt;/p&gt;
&lt;p&gt;These are the kinds of questions the &lt;a href=&#34;https://sites.google.com/view/crowdcountingconsortium/home&#34;&gt;Crowd Counting Consortium&lt;/a&gt; (CCC) Crowd Dataset helps answer. Begun after the 2017 Women’s March by Professors &lt;a href=&#34;https://www.ericachenoweth.com/&#34;&gt;Erica Chenoweth&lt;/a&gt; (Harvard University) and &lt;a href=&#34;https://jeremy-pressman.uconn.edu/&#34;&gt;Jeremy Pressman&lt;/a&gt; (University of Connecticut), the CCC’s database on political crowds has grown into one of the most comprehensive open sources of near-real time information on protests, marches, demonstrations, strikes, and similar political gatherings in the contemporary United States. At the start of August 2020, the database included nearly 50,000 events. These data have been used in numerous academic and press pieces, including a recent &lt;a href=&#34;https://www.nytimes.com/interactive/2020/07/03/us/george-floyd-protests-crowd-size.html&#34;&gt;&lt;em&gt;New York Times&lt;/em&gt;&lt;/a&gt; story on the historic scale of this year’s Black Lives Matter uprising.&lt;/p&gt;
&lt;p&gt;As rich as the data are, they have been a challenge to use. The CCC shares its data on political crowds via a &lt;a href=&#34;https://sites.google.com/view/crowdcountingconsortium/view-download-the-data&#34;&gt;stack of monthly Google Sheets&lt;/a&gt; with formats that can vary from sheet to sheet in small but confounding ways. Column names don’t always match, and certain columns have been added or dropped over time. Some sheets include separate tabs for specific macro-events or campaigns (e.g., a coordinated climate strike), while others group everything in a single sheet. And, of course, typos happen.&lt;/p&gt;
&lt;p&gt;To make this tremendous resource more accessible to researchers, activists, journalists, and data scientists, the &lt;a href=&#34;https://carrcenter.hks.harvard.edu/non-violent-social-movements&#34;&gt;Nonviolent Action Lab&lt;/a&gt; at Harvard’s &lt;a href=&#34;https://carrcenter.hks.harvard.edu/&#34;&gt;Carr Center for Human Rights Policy&lt;/a&gt;—a new venture started by CCC co-founder Chenoweth—has created a &lt;a href=&#34;https://github.com/nonviolent-action-lab/crowd-counting-consortium&#34;&gt;GitHub repository&lt;/a&gt; to host a compiled, cleaned, and augmented version of the CCC’s database.&lt;/p&gt;
&lt;p&gt;In addition to all the information contained in the monthly sheets, the compiled version adds two big feature sets.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Geolocation.&lt;/strong&gt; After compiling the data, the Lab uses the &lt;a href=&#34;https://cran.r-project.org/web/packages/googleway/index.html&#34;&gt;googleway&lt;/a&gt; package to run the cities and towns in which the events took place through Google Maps’s &lt;a href=&#34;https://developers.google.com/maps/documentation/geolocation/overview&#34;&gt;Geolocation API&lt;/a&gt; and extracts geocoordinates from the results, along with clean versions of the locality, county, and state names associated with them.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Issue Tags.&lt;/strong&gt; In the original data, protesters’ claims—in other words, what the protest is about—are recorded by human coders in a loosely structured way. To allow researchers to group or filter the data by theme, the Nonviolent Action Lab maintains a dictionary of a few dozen major political issues in the U.S. (e.g., “guns”, “migration”, “racism”) and keyword– and keyphrase-based regular expressions associated with them. By mapping this dictionary over the claim strings, we generate a set of binary issue tags that gets added to the compiled database as a vector of semicolon-separated strings.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To make the CCC data more accessible to a wider audience, the Lab has also built a &lt;a href=&#34;https://nonviolentactionlab.shinyapps.io/ccc-data-dashboard/&#34;&gt;Shiny dashboard&lt;/a&gt; that lets users filter events in various ways and then map and plot the results. Users can filter by date range, year, or campaign as well as issue and political valence (pro-Trump, anti-Trump, or neither).&lt;/p&gt;
&lt;p&gt;The dashboard has two main tabs. The first uses the &lt;a href=&#34;https://cran.r-project.org/web/packages/leaflet/index.html&#34;&gt;leaflet&lt;/a&gt; package to map the events with markers that contain summary details and links to the source(s) the human coders used to research them.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;map_view.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The second tab uses &lt;a href=&#34;https://cran.r-project.org/web/packages/plotly/index.html&#34;&gt;plotly&lt;/a&gt; and the &lt;a href=&#34;https://hrbrmstr.github.io/streamgraph/&#34;&gt;streamgraph&lt;/a&gt; html widget package to render interactive plots of trends over time in the occurrence of the selected events, the number of participants in them, and the political issues associated with them.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;plot_view.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The point of the Nonviolent Action Lab’s &lt;a href=&#34;https://github.com/nonviolent-action-lab/crowd-counting-consortium&#34;&gt;repository&lt;/a&gt; and &lt;a href=&#34;https://nonviolentactionlab.shinyapps.io/ccc-data-dashboard/&#34;&gt;dashboard&lt;/a&gt; is to make the Crowd Counting Consortium’’s data more accessible and more useful to as wide an audience as possible. If you use either of these resources and find bugs or errors or have suggestions on how to improve them, please let us know.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;To provide feedback on the compiled data set or the Shiny dashboard, please open an issue on the GitHub repository, &lt;a href=&#34;https://github.com/nonviolent-action-lab/crowd-counting-consortium/issues&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If you think you see an error in the CCC’s data or know about an event that it doesn’t cover, please use &lt;a href=&#34;https://sites.google.com/view/crowdcountingconsortium/submit-a-record&#34;&gt;this form&lt;/a&gt; to submit a correction or record via the CCC website.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2020/08/31/crowd-counting-consortium-crowd-data-and-shiny-dashboard/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Some Select COVID-19 Modeling Resources</title>
      <link>https://rviews.rstudio.com/2020/04/07/some-select-covid-19-modeling-resources/</link>
      <pubDate>Tue, 07 Apr 2020 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2020/04/07/some-select-covid-19-modeling-resources/</guid>
      <description>
        


&lt;p&gt;There is an incredible amount of COVID-19 related material available online. While many dashboards, data sets, shiny apps and models represent significant contributions towards fighting the pandemic, we seem to have reached a point where we should be thinking about standards of quality, and should be exploring avenues for cooperation before launching more individual efforts. Below are a few examples of what I believe are exemplars of different types of COVID-19 related contributions. Please feel free to criticize my choices, or suggest other examples of quality contributions in the comments following this post.&lt;/p&gt;
&lt;div id=&#34;a-shiny-app&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A Shiny App&lt;/h3&gt;
&lt;p&gt;At the top of my list is the Shiny based model: &lt;a href=&#34;https://alhill.shinyapps.io/COVID19seir/&#34;&gt;Modeling COVID-19 Spread vs Healthcare Capacity&lt;/a&gt; developed by Alison Hill of Harvard’s Program for Evolutionary Dynamics with contributions from several researchers at the University of Pennsylvania, Harvard and Iowa State. Some things I really like about this app are: (1) that it provides enough background information to be self-documenting and self-contained. (2) The interactive visualizations are without unnecessary adornment and clearly labeled. (3) Default settings for sliders and other parameters are mostly based on documented data. (4) The differential equation theory underlying the model is clearly presented with the intention of helping model users understand the math. The content behind Model and Tutorial tabs sets a standard of excellence for concise explanations within the limits of the form factor. (5) The extensive documentation under the Sources tab inspires confidence and opens wide a window to this field of health care planning. (6) The &lt;a href=&#34;https://github.com/alsnhll/SEIR_COVID19&#34;&gt;code&lt;/a&gt; is straightforward and well organized. I believe that anyone developing a Shiny app for use by professionals would do well to try and meet or exceed the standard set by this app.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-curious-number&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A Curious Number&lt;/h3&gt;
&lt;p&gt;To me, no single number in the catalog of COVID-19 models is more alluring, or cloaked in deeper mystery than R&lt;sub&gt;0&lt;/sub&gt;, the reproduction number. So I was delighted to discover James Holland Jones’ 2007 &lt;a href=&#34;https://web.stanford.edu/~jhj1/teachingdocs/Jones-on-R0.pdf&#34;&gt;Notes on R&lt;sub&gt;0&lt;/sub&gt;&lt;/a&gt;, a very readable account of the assumptions and mathematics that underlie this parameter that provides links for those who want an even deeper understanding.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;some-prominent-r-packages&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Some Prominent R Packages&lt;/h3&gt;
&lt;p&gt;The &lt;a href=&#34;https://www.repidemicsconsortium.org/projects/&#34;&gt;R packages&lt;/a&gt; from the &lt;a href=&#34;https://www.repidemicsconsortium.org/&#34;&gt;R Epidemics Consortium&lt;/a&gt; are tools for professional epidemiologists. See the Tim Churches &lt;a href=&#34;&#34;&gt;3/19 post&lt;/a&gt; for an example of using &lt;a href=&#34;https://cran.r-project.org/package=EpiModel&#34;&gt;EpiModel&lt;/a&gt; and his &lt;a href=&#34;https://rviews.rstudio.com/2020/03/05/covid-19-epidemiology-with-r/&#34;&gt;3/5 post&lt;/a&gt; for and example using &lt;a href=&#34;https://cran.r-project.org/package=earlyR&#34;&gt;earlyR&lt;/a&gt; and &lt;a href=&#34;https://cran.r-project.org/package=EpiEstim&#34;&gt;EpiEstim&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-site-for-researchers&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A Site for Researchers&lt;/h3&gt;
&lt;p&gt;The comprehensive &lt;a href=&#34;https://ourworldindata.org/coronavirus&#34;&gt;Coronavirus Disease (COVID-19) Statistics and Research&lt;/a&gt; site by Max Roser, Hannah Ritchie and Esteban Ortiz-Ospina offers a global view of the pandemic that is updated daily.&lt;/p&gt;
&lt;iframe width=&#34;1000&#34; height=&#34;700&#34; src=&#34;https://ourworldindata.org/grapher/covid-deaths-days-since-per-million&#34;&gt;
&lt;/iframe&gt;
&lt;/div&gt;
&lt;div id=&#34;a-few-dashboards&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A Few Dashboards&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The Johns Hopkins &lt;a href=&#34;https://coronavirus.jhu.edu/data&#34;&gt;Data Center&lt;/a&gt; provides daily updates on &lt;a href=&#34;https://coronavirus.jhu.edu/data/new-cases&#34;&gt;New Cases&lt;/a&gt;, &lt;a href=&#34;https://coronavirus.jhu.edu/data/mortality&#34;&gt;Mortality&lt;/a&gt; and &lt;a href=&#34;https://coronavirus.jhu.edu/data/cumulative-cases&#34;&gt;Cumulative Cases&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;The New York Times &lt;a href=&#34;https://www.nytimes.com/interactive/2020/us/coronavirus-us-cases.html&#34;&gt;Coronavirus in the U.S.: Latest Map and Case Count&lt;/a&gt; page is an excellent way to drill down into U.S. State and County data.&lt;/li&gt;
&lt;li&gt;The USAFACTS &lt;a href=&#34;https://usafacts.org/visualizations/coronavirus-covid-19-spread-map/&#34;&gt;Coronavirus in the United States&lt;/a&gt;: Mapping the COVID-19 outbreak in the states and counties aggregates CDC data directly harvested from state and local agencies accessed through the &lt;a href=&#34;https://www.cdc.gov/publichealthgateway/healthdirectories/healthdepartments.html&#34;&gt;Public Health Professionals Gateway&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;two-high-impact-blog-posts&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Two High Impact Blog Posts&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Tomas Pueyo’s &lt;a href=&#34;https://medium.com/@tomaspueyo/coronavirus-act-today-or-people-will-die-f4d3d9cd99ca&#34;&gt;3/10 post&lt;/a&gt; which raised the alarm in American Statistical Association circles is still worth reading. The alarming predictions of human suffering backed up by data visualizations make an emotional impact. This post also displays the the masterful graph from the by Wu and McGoogan’s &lt;a href=&#34;https://jamanetwork.com/journals/jama/fullarticle/2762130&#34;&gt;JAMA paper&lt;/a&gt; showing the early history of the outbreak in Wuhan.
&lt;img src=&#34;jvp.png&#34; height = &#34;800&#34; width=&#34;1000&#34;&gt;&lt;/li&gt;
&lt;li&gt;Terry Tao’s &lt;a href=&#34;https://terrytao.wordpress.com/2020/03/25/polymath-proposal-clearinghouse-for-crowdsourcing-covid-19-data-and-data-cleaning-requests/&#34;&gt;March 25th post&lt;/a&gt; which announces the Christopher Strohmeier &lt;a href=&#34;https://terrytao.files.wordpress.com/2020/03/covid_19_polymath_project-1.pdf&#34;&gt;COVID-19 Polymath Proposal&lt;/a&gt; initiated a valuable discussion on relevant data sets. See the &lt;a href=&#34;https://asone.ai/polymath/index.php?title=COVID-19_dataset_clearinghouse&#34;&gt;Covid-19 dataset clearinghouse&lt;/a&gt; wiki.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;some-data&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Some Data&lt;/h3&gt;
&lt;p&gt;In addition to the data behind some of the above links, you may find the following data sources useful. The Johns Hopkins COVID-19 data seems to have become the defacto standard for COVID-19 modeling. You can directly download: &lt;a href=&#34;https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv%22&#34;&gt;time_series_covid19_confirmed_global.csv&lt;/a&gt; and &lt;a href=&#34;https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv&#34;&gt;time_series_covid19_deaths_global.csv&lt;/a&gt;. Additionally, both &lt;a href=&#34;https://coronavirus-disasterresponse.hub.arcgis.com/datasets/51b7109ab2cc49e29783babad27d64a2&#34;&gt;esri&lt;/a&gt; and &lt;a href=&#34;https://data.world/&#34;&gt;data.world&lt;/a&gt; (See &lt;a href=&#34;https://data.world/resources/coronavirus/?utm_campaign=data_digest&amp;amp;utm_source=email&amp;amp;utm_medium=email&amp;amp;utm_content=200326&amp;amp;_hsenc=p2ANqtz-8scgcZFzV0YyRZzOxDkZ8rUQuyshmWP_PyCXEy9HbIiiQ5KpZanf2VfHIKZySJpjMEtVhaFOuR4BniV0vzpfm-hlxmhM5yAQujLmTHAbAsZFoE6Y8&amp;amp;_hsmi=85975097&#34;&gt;The Corononavirus (COVID-19) Data Resource Hub&lt;/a&gt;) provide a number of curated COVID-19 data sets.&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2020/04/07/some-select-covid-19-modeling-resources/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>R, Public Health and Politics</title>
      <link>https://rviews.rstudio.com/2020/02/19/r-public-health-and-politics/</link>
      <pubDate>Wed, 19 Feb 2020 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2020/02/19/r-public-health-and-politics/</guid>
      <description>
        &lt;p&gt;Last week, Lancet published the paper &lt;a href=&#34;https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(19)33019-3/fulltext#%20&#34;&gt;&lt;em&gt;Improving the prognosis of health care in the USA&lt;/em&gt;&lt;/a&gt; by Alison P Galvani, Alyssa S Parpia, Eric M Foster, Burton H Singer, Meagan C Fitzpatrick of &lt;a href=&#34;https://publichealth.yale.edu/cidma/&#34;&gt;CIDMA&lt;/a&gt;, the Center for Infectious Disease Modeling and Analysis, Yale School of Public Health. The paper, which, provides a detailed analysis of the single-payer system introduced by Senator Sanders in the &lt;a href=&#34;https://www.sanders.senate.gov/download/
medicare-for-all-act?id=6CA2351C-6EAE-4A11-BBE4-CE07984813C8
&amp;amp;download=1&amp;amp;inline=file&#34;&gt;Medicare for All Act&lt;/a&gt; was published with a Shiny application that allows readers to test key assumptions regarding health care budgets, projected revenue, and the projected expansion of health care use.&lt;/p&gt;

&lt;p&gt;While the authors are clearly arguing the case for the single-payer system, the publication in a prestigious peer-reviewed journal, the detailed, documented data presented, and the Shiny app for testing assumptions should make this paper the basis for all serious, rational discussion about the economic viability of the single-payer system.&lt;/p&gt;

&lt;p&gt;This Shiny app is also a milestone for R, as it demonstrates the ability of R to help experts interactively engage with informed citizens to help them develop their own insights on complex matters.&lt;/p&gt;

&lt;iframe src=&#34;https://shift-cidma.shinyapps.io/single-payer_healthcare_interactive_financing_tool/&#34; width = 100% height = 1200&gt;&lt;/iframe&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2020/02/19/r-public-health-and-politics/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>No Framework, No Problem! Structuring your project folder and creating custom Shiny components</title>
      <link>https://rviews.rstudio.com/2020/01/13/no-framework-no-problem-structuring-your-project-folder-and-creating-custom-shiny-components/</link>
      <pubDate>Mon, 13 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2020/01/13/no-framework-no-problem-structuring-your-project-folder-and-creating-custom-shiny-components/</guid>
      <description>
        

&lt;p&gt;&lt;em&gt;Pedro Coutinho Silva is a software engineer at Appsilon Data Science.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;It is not always possible to create a dashboard that fully meets your expectations or requirements using only existing libraries. Maybe you want a specific function that needs to be custom built, or maybe you want to add your own style or company branding. Whatever the case, a moment might come when you need to expand and organize your code base, and dive into creating a custom solution for your project; but where to start? In this post, I will explain the relevant parts of my workflow for Shiny projects using our hiring funnel application as an example.&lt;/p&gt;

&lt;p&gt;&lt;img src=&#34;dashboard.png&#34; alt=&#34;Hiring Funnel Dashboard&#34; /&gt;&lt;/p&gt;

&lt;p&gt;I will cover:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Structuring the project folder: what goes where?

&lt;ul&gt;
&lt;li&gt;Managers and extracting values into settings files.&lt;/li&gt;
&lt;li&gt;Using modules to organize your code.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;What does it actually take to create a custom component?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hopefully, these topics will be as valuable to you as they have been to me!&lt;/p&gt;

&lt;h3 id=&#34;structuring-your-project-folder&#34;&gt;Structuring your project folder&lt;/h3&gt;

&lt;p&gt;Your typical dashboard project doesn&amp;rsquo;t have a very complex structure, but this can change a lot as your project grows, so I typically try to keep things as separate as possible, and to provide some guidance for future collaborators.&lt;/p&gt;

&lt;p&gt;I wont go over styles since these are basically an implementation of &lt;a href=&#34;https://github.com/rstudio/sass&#34;&gt;Sass&lt;/a&gt;. Sass lets you keep your sanity while avoiding inline styling. You can read a bit more about it on my &lt;a href=&#34;https://appsilon.com/how-to-make-your-css-awesome-with-sass/&#34;&gt;previous post&lt;/a&gt; about it.&lt;/p&gt;

&lt;p&gt;So what does our project folder actually look like? Here is our &lt;a href=&#34;https://appsilon.com/journey-from-basic-prototype-to-production-ready-shiny-dashboard/&#34;&gt;hiring funnel&lt;/a&gt; project folder for example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;│ app.R
└─── app
    │ global.R
    │ server.R
    │ ui.R
    └─── managers
    │ constants_manager.R
    │ data_manager.R
    └─── settings
    │ app.json
    │ texts.json
    └─── modules
    │ header.R
    │ sidebar.R
    │ ui_components.R
    └─── styles
    │   │ main.scss
    │  ...
    └─── www
        │ sass.min.css
        └─── assets
        └─── scripts
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Quite a lot to unpack, but lets go over the important bits:&lt;/p&gt;

&lt;h3 id=&#34;managers-and-settings&#34;&gt;Managers and Settings&lt;/h3&gt;

&lt;p&gt;Managers are scripts that make use of R6 classes. The constants manager has already been covered before by one of my colleagues in &lt;a href=&#34;https://appsilon.com/super-solutions-for-shiny-architecture-3-5-softcoding-constants-in-the-app/&#34;&gt;the super solutions series&lt;/a&gt;. The data manager contains all of the abstraction when dealing with data loading and processing.&lt;/p&gt;

&lt;p&gt;Settings has all of the values that should not be hard coded. This includes constants, texts and other values that can be extracted.&lt;/p&gt;

&lt;h3 id=&#34;modules&#34;&gt;Modules&lt;/h3&gt;

&lt;p&gt;Modules let you easily create files for managing parts of your code. This means you can have modules for specific elements or even layout sections without bloating your main files too much.&lt;/p&gt;

&lt;p&gt;They are great when it comes to code structure. Let&amp;rsquo;s take our header for example, instead of growing our &lt;code&gt;ui.R&lt;/code&gt; with all of the header code, we can extract it to a separate file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Header.R
import(&amp;quot;shiny&amp;quot;)
import(&amp;quot;modules&amp;quot;)
export(&amp;quot;ui&amp;quot;)

ui_components &amp;lt;- use(&amp;quot;modules/ui_components.R&amp;quot;)

ui &amp;lt;- function(id) {
  tags$header(
    ...
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All it takes is importing the libraries you plan to use, and exporting the functions you would like to make available. You can even call other modules from inside a module!&lt;/p&gt;

&lt;p&gt;After this we just instance the module in &lt;code&gt;UI.R&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# ui.R
header &amp;lt;- use(&amp;quot;modules/header.R&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And can now use by simply calling the function we want:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fluidPage(
  header$ui()
  ...
&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&#34;custom-components&#34;&gt;Custom components&lt;/h3&gt;

&lt;p&gt;When you cannot find a component that does what you want, sometimes the only option is to create it yourself. Since we are talking about HTML components, we can expect the average component to have three main parts:
 - Layout
 - Style
 - Behavior&lt;/p&gt;

&lt;p&gt;We have already covered modules, but how do we deal with styling and behavior? Lets take for example our navigation. What we are looking for behaves as a tab system, but where the navigation is split from the content. So we need two different &lt;code&gt;ui&lt;/code&gt; functions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;tabs_navigation &amp;lt;- function(id = &amp;quot;main-tabs-navigation&amp;quot;, options) {
  tagList(
    tags$head(
      tags$script(src = &amp;quot;scripts/tab-navigation.js&amp;quot;)
    ),
    tags$div(
      id = id,
      class = &amp;quot;tabs-navigation&amp;quot;,
      `data-tab-type`= &amp;quot;navigation&amp;quot;,

      lapply(options, tabs_single_navigation)
    )
  )
}

tabs_panel &amp;lt;- function(
  id = &amp;quot;main_tab_set&amp;quot;,
  class = &amp;quot;tabs-container&amp;quot;,
  tabs_content
) {
  div(
    id = &amp;quot;main-tabs-container&amp;quot;,
    class = &amp;quot;tabs-container&amp;quot;,
    `data-tab-type`= &amp;quot;tabs-container&amp;quot;,

    lapply(tabs_content, single_tab),
    tags$script(&amp;quot;init_tab_navigation()&amp;quot;)
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By giving the different elements id&amp;rsquo;s and classes, we can use sass to easily style these components. And by including a &lt;code&gt;Javascript&lt;/code&gt; file in the element we can load and initialize browser behavior. In this case our &lt;code&gt;tab-navigation.js&lt;/code&gt; just initializes the first tab and binds a click event to cycle through the different tabs when clicked.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;init_tab_navigation = function() {
  $( document ).ready(function() {
    $(&amp;quot;[data-tab-type=&#39;navigation&#39;]&amp;quot;)
      .find(&amp;quot;[data-tab-type=&#39;controller&#39;]&amp;quot;)
      .first().addClass(&amp;quot;active&amp;quot;)

    $(`[data-tab-type=&amp;quot;tabs-container&amp;quot;]`)
      .find(`[data-tab-type=&amp;quot;tab&amp;quot;]`)
      .first().addClass(&amp;quot;active&amp;quot;)

    $(&amp;quot;[data-tab-type=&#39;controller&#39;]&amp;quot;).on(&amp;quot;click&amp;quot;, function(e){
    	$(this)
        .addClass(&amp;quot;active&amp;quot;)
        .siblings(`[data-tab-type=&amp;quot;controller&amp;quot;]`)
        .removeClass(&amp;quot;active&amp;quot;)

      let target = $(this).data(&amp;quot;target&amp;quot;)

      $(`[data-tab-id=&amp;quot;${target}&amp;quot;]`).addClass(&amp;quot;active&amp;quot;)
        .siblings(`[data-tab-type=&amp;quot;tab&amp;quot;]`)
        .removeClass(&amp;quot;active&amp;quot;)
    })
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It takes a bit of effort, but the result is something truly custom.
&lt;img src=&#34;tabs.png&#34; alt=&#34;Hiring Funnel Dashboard&#34; /&gt;&lt;/p&gt;

&lt;p&gt;We barely scratched the surface of what can be done when it comes to custom solutions, but I hope it already gives you an idea of how to start or improve your next project!&lt;/p&gt;

&lt;p&gt;Craving more, or have any questions? Feel free to reach out and ask!&lt;/p&gt;

&lt;h3 id=&#34;references&#34;&gt;References&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Modules (&lt;a href=&#34;https://cran.r-project.org/web/packages/modules/vignettes/modulesInR.html&#34;&gt;https://cran.r-project.org/web/packages/modules/vignettes/modulesInR.html&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Sass (&lt;a href=&#34;https://github.com/rstudio/sass&#34;&gt;https://github.com/rstudio/sass&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;R6 classes (&lt;a href=&#34;https://adv-r.hadley.nz/r6.html&#34;&gt;https://adv-r.hadley.nz/r6.html&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2020/01/13/no-framework-no-problem-structuring-your-project-folder-and-creating-custom-shiny-components/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Introducing sortable to add drag-and-drop to your shiny apps</title>
      <link>https://rviews.rstudio.com/2019/11/26/using-sortable-for-drag-and-drop-in-shiny-apps/</link>
      <pubDate>Tue, 26 Nov 2019 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2019/11/26/using-sortable-for-drag-and-drop-in-shiny-apps/</guid>
      <description>
        


&lt;p&gt;&lt;em&gt;Andrie de Vries is the author of “R for Dummies” and a Solutions Engineer at RStudio&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Earlier this year I was a student on the &lt;a href=&#34;RStudio%20Instructor%20Training&#34;&gt;RStudio Instructor Training&lt;/a&gt;, taught by the inspiratational Greg Wilson. I remember several tips from this course, for example that you should always try to draw a &lt;a href=&#34;https://docs.google.com/presentation/d/1k45SqyM-w4DtK7dmedeX7pk_r8B9Aq0FKKCxC04pTRM/&#34;&gt;concept map&lt;/a&gt; of the material you are teaching. And, secondly, that you should make liberal use of &lt;a href=&#34;https://docs.google.com/presentation/d/1PBxBFpkB4w-C3_l2rWdGMtjxaxDeu8gVP0K0CHJfbdQ/&#34;&gt;formative assessment&lt;/a&gt; during your teaching.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/post/2019-11-26-sortable-part-1_files/concept-map-of-concept-maps.png&#34; /&gt;&lt;!-- --&gt;&lt;/p&gt;
&lt;p&gt;A formative question helps the student grow their understanding of a topic, in contrast to a normative question that attempts to assess the skills of the student. Greg mentioned several archetypal formative questions, including a ranking question. In this type of question, the teacher provides the student with a list of options, and the task is to arrange these items in the correct order. It’s a great formative question, because you’re not testing the student’s memory (you provide all the terms) but you’re testing their understanding and reasoning about the topic.&lt;/p&gt;
&lt;p&gt;This made me wonder what it would take to create ranking type questions in &lt;code&gt;learnr&lt;/code&gt; tutorials. (A &lt;code&gt;learnr&lt;/code&gt; tutorial is a special type of R Markdown document with a &lt;code&gt;shiny&lt;/code&gt; runtime, that allows quizzes and other question types.)&lt;/p&gt;
&lt;p&gt;Now, to be able to rank items in a &lt;code&gt;shiny&lt;/code&gt; app, you first need to enable drag-and-drop behaviour in &lt;code&gt;shiny&lt;/code&gt;. This was not something I had seen at the time (around May 2019), so I went searching…&lt;/p&gt;
&lt;p&gt;Within hours I found a highly experimental (and incomplete) package by Kent Russell, called &lt;code&gt;sortable&lt;/code&gt;. The &lt;code&gt;sortable&lt;/code&gt; package was an &lt;code&gt;htmlwidget&lt;/code&gt; that wrapped the &lt;code&gt;SortableJS&lt;/code&gt; JavaScript library. The &lt;code&gt;SortableJS&lt;/code&gt; &lt;a href=&#34;https://sortablejs.github.io/Sortable/&#34;&gt;library&lt;/a&gt; is a “JavaScript library for reorderable drag-and-drop lists”.&lt;/p&gt;
&lt;p&gt;This sounded exactly what I needed, but there was a snag. Kent started the package during a period where he created a new &lt;code&gt;htmlwidget&lt;/code&gt; every week, and the package itself was functioning, but incomplete. However, the existing functionality was tantalizing - it was possible to reorder all sorts of items in a the &lt;code&gt;shiny&lt;/code&gt; UI, but it was not possible to read the return value. So you could re-order elements, but you could not use this information in a &lt;code&gt;shiny&lt;/code&gt; reactive element. In other words, the &lt;code&gt;shiny&lt;/code&gt; app could not respond to the input.&lt;/p&gt;
&lt;div id=&#34;first-steps-in-updating-the-package&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;First steps in updating the package&lt;/h2&gt;
&lt;p&gt;My first steps in updating the package was to attempt to close the feedback loop. Specifically, I needed the JavaScript object to communicate back to R.&lt;/p&gt;
&lt;p&gt;Fortunately, this is a well-understood problem (at least for the people who wrote &lt;code&gt;htmlwidgets&lt;/code&gt; and &lt;code&gt;shiny&lt;/code&gt;). And I was especially happy that Barret Schloerke was prepared to help me with some pointers.&lt;/p&gt;
&lt;p&gt;In a nutshell, the &lt;code&gt;sortable&lt;/code&gt; package contains a function &lt;code&gt;sortable_js_capture_input()&lt;/code&gt; that does the translation between the &lt;code&gt;htmlwidget&lt;/code&gt; and the &lt;code&gt;shiny&lt;/code&gt; app.&lt;/p&gt;
&lt;p&gt;Most users of &lt;code&gt;sortable&lt;/code&gt; do not need to know this, but the function takes a &lt;code&gt;shiny&lt;/code&gt; input ID as input, runs some JavaScript to modify the &lt;code&gt;shiny&lt;/code&gt; object:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sortable_js_capture_input &amp;lt;- function(input_id) {
  # can call jquery as shiny will always have jquery
  inner_text &amp;lt;- paste0(
    &amp;quot;$.map(&amp;quot;,
    &amp;quot;  this.el.children, &amp;quot;,
    get_child_id_or_text_js_fn(),
    &amp;quot;)&amp;quot;,
    collapse = &amp;quot;\n&amp;quot;
  )
  js_text &amp;lt;- &amp;quot;function(evt) {
  if (typeof Shiny !== \&amp;quot;undefined\&amp;quot;) {
    Shiny.setInputValue(\&amp;quot;%s:sortablejs.rank_list\&amp;quot;, %s)
  }
}&amp;quot;

  js &amp;lt;- sprintf(js_text, input_id, inner_text)

  htmlwidgets::JS(js)
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;magic-can-happen-with-sortable&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Magic can happen with sortable&lt;/h2&gt;
&lt;p&gt;Once it was possible to capture the input from &lt;code&gt;SortableJS&lt;/code&gt; and pass this value to the shiny input object, it was possible to create some magic.&lt;/p&gt;
&lt;p&gt;For example, in the original version of the package, Kent Russell wrote a simplified version of a shiny app that let’s the user drag-and-drop the columns of a data frame into separate lists.&lt;/p&gt;
&lt;p&gt;Once the shiny app knows what the values of these input lists are, it is quite simple to draw a plot based on these inputs:&lt;/p&gt;
&lt;video height=&#34;400px&#34;controls&gt;
&lt;source src=&#34;https://s3.amazonaws.com/rviews.rstudio.com/2019-11-26-sortable/sortable-magic.mp4&#34; type=&#34;video/mp4&#34;&gt;
&lt;/video&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;You can try the app at &lt;a href=&#34;https://andrie-de-vries.shinyapps.io/sortable_drag_vars_to_plot_app/&#34; class=&#34;uri&#34;&gt;https://andrie-de-vries.shinyapps.io/sortable_drag_vars_to_plot_app/&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;using-the-package&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Using the package&lt;/h2&gt;
&lt;p&gt;The package is not yet available from CRAN, but you can find the development version at &lt;a href=&#34;https://github.com/rstudio/sortable&#34; class=&#34;uri&#34;&gt;https://github.com/rstudio/sortable&lt;/a&gt;, and the &lt;code&gt;pkgdown&lt;/code&gt; documentation at &lt;a href=&#34;https://rstudio.github.io/sortable/&#34; class=&#34;uri&#34;&gt;https://rstudio.github.io/sortable/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To install the development version, use:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;remotes&amp;quot;)
remotes::install_github(&amp;quot;rstudio/sortable&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then you can try any of the examples in the documentation. For example, to run the &lt;code&gt;shiny&lt;/code&gt; app with drag-and-drop plots, try:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;shiny::runApp(system.file(&amp;quot;shiny-examples/drag_vars_to_plot&amp;quot;, package = &amp;quot;sortable&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;what-happened-next&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;What happened next&lt;/h2&gt;
&lt;p&gt;I was excited about the potential of the package, so I contacted Kent Russell. In turn, he was delighted that somebody took his idea and built on it, so we agreed that I will maintain the package, with the substantial help of Barret Schloerke.&lt;/p&gt;
&lt;p&gt;At the start of this post I said my initial inspiration was to find a way to create ranking questions in &lt;code&gt;learnr&lt;/code&gt; tutorials.&lt;/p&gt;
&lt;p&gt;But that’s actually another long story, and I will tell the story of custom question types and &lt;code&gt;question_rank()&lt;/code&gt; in a follow-on to this post in the near future.&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2019/11/26/using-sortable-for-drag-and-drop-in-shiny-apps/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Building Interactive World Maps in Shiny</title>
      <link>https://rviews.rstudio.com/2019/10/09/building-interactive-world-maps-in-shiny/</link>
      <pubDate>Wed, 09 Oct 2019 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2019/10/09/building-interactive-world-maps-in-shiny/</guid>
      <description>
        


&lt;p&gt;&lt;em&gt;Florianne Verkroost is a PhD candidate at Nuffield College at the University of Oxford. With a passion for data science and a background in mathematics and econometrics. She applies her interdisciplinary knowledge to computationally address societal problems of inequality.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;In this post, I will show you how to create interactive world maps and how to show these in the form of an R Shiny app. As the Shiny app cannot be embedded into this blog, I will direct you to the &lt;a href=&#34;https://fverkroost.shinyapps.io/interactive_worldmap_app/&#34;&gt;live app&lt;/a&gt; and show you in &lt;a href=&#34;https://github.com/fverkroost/RStudio-Blogs/blob/master/interactive_worldmap_shiny_embedded.Rmd&#34;&gt;this post&lt;/a&gt; on my GitHub how to embed a Shiny app in your R Markdown files, which is a really cool and innovative way of preparing interactive documents. To show you how to adapt the interface of the app to the choices of the users, we’ll make use of two data sources such that the user can choose what data they want to explore, and that the app adapts the possible input choices to the users’ previous choices. The data sources here are about childlessness and gender inequality, which is the focus of my PhD research, in which I computationally analyse the effects of gender and parental status on socio-economic inequalities.&lt;/p&gt;
&lt;p&gt;We’ll start by loading and cleaning the data, whereafter we will build our interactive world maps in R Shiny. Let’s first load the required packages into RStudio.&lt;/p&gt;
&lt;div id=&#34;section-importing-exploring-and-cleaning-the-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Importing, exploring and cleaning the data&lt;/h2&gt;
&lt;p&gt;Now, we can continue with loading our data. As we’ll make world maps, we need a way to map our data sets to geographical data containing coordinates (longitude and latitude). As different data sets have different formats for country names (e.g., “United Kingdom of Great Britain and Northern Ireland” versus “United Kingdom”), we’ll match country names to ISO3 codes to easily merge all data sets later on. Therefore, we first scrape an HTML table of country names, ISO3, ISO2 and UN codes for all countries worldwide. We use the &lt;code&gt;rvest&lt;/code&gt; package using the XPath to indicate what part of the web page contains our table of interest. We use the pipe (%&amp;gt;%) from the &lt;code&gt;magrittr&lt;/code&gt; package to feed our URL of interest into functions that read the HTML table using the XPath and convert that to a data frame in R. One can obtain the XPath by hovering over the HTML table in developer mode in the browser, and having it show the XPath.&lt;/p&gt;
&lt;p&gt;The first element in the resulting list contains our table of interest, and as the first column is empty, we delete it. Also, as you can see from the HTML table in the link, there are some rows that show the letter of the alphabet before starting with a list of countries of which the name starts with that letter. As these rows contain the particular letter in all columns, we can delete these by deleting all rows for which all columns have equal values.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(magrittr)
library(rvest)
url &amp;lt;- &amp;quot;https://www.nationsonline.org/oneworld/country_code_list.htm&amp;quot;
iso_codes &amp;lt;- url %&amp;gt;%
  read_html() %&amp;gt;%
  html_nodes(xpath = &amp;#39;//*[@id=&amp;quot;CountryCode&amp;quot;]&amp;#39;) %&amp;gt;%
  html_table()
iso_codes &amp;lt;- iso_codes[[1]][, -1]
iso_codes &amp;lt;- iso_codes[!apply(iso_codes, 1, function(x){all(x == x[1])}), ]
names(iso_codes) &amp;lt;- c(&amp;quot;Country&amp;quot;, &amp;quot;ISO2&amp;quot;, &amp;quot;ISO3&amp;quot;, &amp;quot;UN&amp;quot;)
head(iso_codes)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##          Country ISO2 ISO3  UN
## 2    Afghanistan   AF  AFG 004
## 3  Aland Islands   AX  ALA 248
## 4        Albania   AL  ALB 008
## 5        Algeria   DZ  DZA 012
## 6 American Samoa   AS  ASM 016
## 7        Andorra   AD  AND 020&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we’ll collect our first data set, which is a data set on childlessness provided by the United Nations. We download the file from the link, save it locally, and then load it into RStudio using the &lt;code&gt;read_excel()&lt;/code&gt; function in the &lt;code&gt;readxl&lt;/code&gt; package.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(readxl)
url &amp;lt;- &amp;quot;https://www.un.org/en/development/desa/population/publications/dataset/fertility/wfr2012/Data/Data_Sources/TABLE%20A.8.%20%20Percentage%20of%20childless%20women%20and%20women%20with%20parity%20three%20or%20higher.xlsx&amp;quot;
destfile &amp;lt;- &amp;quot;dataset_childlessness.xlsx&amp;quot;
download.file(url, destfile)
childlessness_data &amp;lt;- read_excel(destfile)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(childlessness_data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 6 x 17
##   `United Nations… ...2  ...3  ...4  ...5  ...6  ...7  ...8  ...9  ...10
##   &amp;lt;chr&amp;gt;            &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt;
## 1 &amp;quot;TABLE  A.8. PE… &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt; 
## 2 Country          ISO … Peri… Refe… Perc… &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  Perc… &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt; 
## 3 &amp;lt;NA&amp;gt;             &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  &amp;lt;NA&amp;gt;  35-39 40-44 45-49 35-39 40-44 45-49
## 4 Afghanistan      4     Earl… ..    ..    ..    ..    ..    ..    ..   
## 5 Afghanistan      4     Midd… ..    ..    ..    ..    ..    ..    ..   
## 6 Afghanistan      4     Late… 2010  2.6   2.6   2.1   93.8  94.5  94   
## # … with 7 more variables: ...11 &amp;lt;chr&amp;gt;, ...12 &amp;lt;chr&amp;gt;, ...13 &amp;lt;chr&amp;gt;,
## #   ...14 &amp;lt;chr&amp;gt;, ...15 &amp;lt;chr&amp;gt;, ...16 &amp;lt;chr&amp;gt;, ...17 &amp;lt;lgl&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can see that the childlessness data are a bit messy, especially when it comes to the first couple of rows and column names. We only want to maintain the columns that have country names, periods, and childlessness estimates for different age groups, as well as the rows that refer to data for specific countries. The resulting data look much better. Note that when we convert the childlessness percentage columns to numeric type later on, the “..” values will automatically change to NA.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cols &amp;lt;- which(grepl(&amp;quot;childless&amp;quot;, childlessness_data[2, ]))
childlessness_data &amp;lt;- childlessness_data[-c(1:3), c(1, 3, cols:(cols + 2))]
names(childlessness_data) &amp;lt;- c(&amp;quot;Country&amp;quot;, &amp;quot;Period&amp;quot;, &amp;quot;35-39&amp;quot;, &amp;quot;40-44&amp;quot;, &amp;quot;45-49&amp;quot;)
head(childlessness_data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 6 x 5
##   Country     Period  `35-39` `40-44` `45-49`
##   &amp;lt;chr&amp;gt;       &amp;lt;chr&amp;gt;   &amp;lt;chr&amp;gt;   &amp;lt;chr&amp;gt;   &amp;lt;chr&amp;gt;  
## 1 Afghanistan Earlier ..      ..      ..     
## 2 Afghanistan Middle  ..      ..      ..     
## 3 Afghanistan Latest  2.6     2.6     2.1    
## 4 Albania     Earlier 7.2     5.5     5.2    
## 5 Albania     Middle  ..      ..      ..     
## 6 Albania     Latest  4.8     4.3     3.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our second data set is about measures of gender inequality, provided by the World Bank. We read this .csv file directly into RStudio from the URL link.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;gender_index_data &amp;lt;- read.csv(&amp;quot;https://s3.amazonaws.com/datascope-ast-datasets-nov29/datasets/743/data.csv&amp;quot;)
head(gender_index_data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Country.ISO3 Country.Name Indicator.Id
## 1          AGO       Angola        27959
## 2          AGO       Angola        27960
## 3          AGO       Angola        27961
## 4          AGO       Angola        27962
## 5          AGO       Angola        28158
## 6          AGO       Angola        28159
##                                                           Indicator
## 1                                   Overall Global Gender Gap Index
## 2                  Global Gender Gap Political Empowerment subindex
## 3                  Global Gender Gap Political Empowerment subindex
## 4                                   Overall Global Gender Gap Index
## 5 Global Gender Gap Economic Participation and Opportunity Subindex
## 6 Global Gender Gap Economic Participation and Opportunity Subindex
##   Subindicator.Type   X2006    X2007    X2008    X2009   X2010   X2011
## 1             Index  0.6038   0.6034   0.6032   0.6353  0.6712  0.6624
## 2              Rank 81.0000  92.0000 103.0000  36.0000 24.0000 24.0000
## 3             Index  0.0696   0.0696   0.0711   0.2007  0.2901  0.2898
## 4              Rank 96.0000 110.0000 114.0000 106.0000 81.0000 87.0000
## 5              Rank 69.0000  87.0000  87.0000  96.0000 76.0000 96.0000
## 6             Index  0.5872   0.5851   0.5843   0.5832  0.6296  0.5937
##   X2012   X2013    X2014   X2015   X2016   X2018
## 1    NA  0.6659   0.6311   0.637   0.643   0.633
## 2    NA 34.0000  38.0000  38.000  40.000  58.000
## 3    NA  0.2614   0.2402   0.251   0.251   0.206
## 4    NA 92.0000 121.0000 126.000 117.000 125.000
## 5    NA 92.0000 111.0000 116.000 120.000 113.000
## 6    NA  0.6163   0.5878   0.590   0.565   0.602&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Luckily, these data are better structured than the childlessness data. The data contains gender inequality measures per year, and for convenience we add a new column with the values for the most recent year for which data are available. In this post, we’ll only look at the rank indicators rather than indices and normalized scores. We drop the Subindicator and IndicatorID columns using the &lt;code&gt;select()&lt;/code&gt; function from the &lt;code&gt;dplyr&lt;/code&gt; package, as we won’t need these further.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)
gender_index_data[&amp;quot;RecentYear&amp;quot;] &amp;lt;- apply(gender_index_data, 1, function(x){as.numeric(x[max(which(!is.na(x)))])})
gender_index_data &amp;lt;- gender_index_data[gender_index_data$Subindicator.Type == &amp;quot;Rank&amp;quot;, ] %&amp;gt;% 
  select(-Subindicator.Type, -Indicator.Id)
names(gender_index_data) &amp;lt;- c(&amp;quot;ISO3&amp;quot;, &amp;quot;Country&amp;quot;, &amp;quot;Indicator&amp;quot;, as.character(c(2006:2016, 2018)), &amp;quot;RecentYear&amp;quot;)
head(gender_index_data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    ISO3 Country
## 2   AGO  Angola
## 4   AGO  Angola
## 5   AGO  Angola
## 7   AGO  Angola
## 9   AGO  Angola
## 11  AGO  Angola
##                                                                                           Indicator
## 2                                                  Global Gender Gap Political Empowerment subindex
## 4                                                                   Overall Global Gender Gap Index
## 5                                 Global Gender Gap Economic Participation and Opportunity Subindex
## 7                                                 Global Gender Gap Educational Attainment Subindex
## 9                                                    Global Gender Gap Health and Survival Subindex
## 11 Wage equality between women and men for similar work (survey data, normalized on a 0-to-1 scale)
##    2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2018 RecentYear
## 2    81   92  103   36   24   24   NA   34   38   38   40   58         58
## 4    96  110  114  106   81   87   NA   92  121  126  117  125        125
## 5    69   87   87   96   76   96   NA   92  111  116  120  113        113
## 7   107  119  122  127  125  126   NA  127  138  141  138  143        143
## 9     1    1    1    1    1    1   NA    1   61    1    1    1          1
## 11   NA   NA   NA   NA   NA   NA   NA   NA   NA   NA  135   94         94&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we load in our world data with geographical coordinates directly from the &lt;code&gt;ggplot2&lt;/code&gt; package. These data contain geographical coordinates of all countries worldwide, which we’ll later need to plot the worldmaps.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(maps)
library(ggplot2)
world_data &amp;lt;- ggplot2::map_data(&amp;#39;world&amp;#39;)
world_data &amp;lt;- fortify(world_data)
head(world_data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     long   lat group order region subregion
## 1 -69.90 12.45     1     1  Aruba      &amp;lt;NA&amp;gt;
## 2 -69.90 12.42     1     2  Aruba      &amp;lt;NA&amp;gt;
## 3 -69.94 12.44     1     3  Aruba      &amp;lt;NA&amp;gt;
## 4 -70.00 12.50     1     4  Aruba      &amp;lt;NA&amp;gt;
## 5 -70.07 12.55     1     5  Aruba      &amp;lt;NA&amp;gt;
## 6 -70.05 12.60     1     6  Aruba      &amp;lt;NA&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To map our data, we need to merge the childlessness, gender gap index, and world map data. As I said before, these all have different notations for country names, which is why we’ll use the ISO3 codes. However, even between the ISO code data and the other data sets, there is discrepancy in country names. Unfortunately, to solve this, we need to manually change some country names in our data to match those in the ISO code data set. The code for doing so is long and tedious, so I won’t show that here, but for your reference you can find it &lt;a href=&#34;https://github.com/fverkroost/RStudio-Blogs/blob/master/interactive_worldmap_shiny_app.R&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now that the name changes for countries have been made, we can add the ISO3 codes to our childlessness and world map data. The gender gap index data already contain these codes, so there’s no need for us to add these there.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;childlessness_data[&amp;#39;ISO3&amp;#39;] &amp;lt;- iso_codes$ISO3[match(childlessness_data$Country, iso_codes$Country)]
world_data[&amp;quot;ISO3&amp;quot;] &amp;lt;- iso_codes$ISO3[match(world_data$region, iso_codes$Country)]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we melt the childlessness and gender gap index data into long format such that they will have similar shape and column names for merging. The &lt;code&gt;melt()&lt;/code&gt; function is included in package &lt;code&gt;reshape2&lt;/code&gt;. The goal here is to create variables that have different unique values for the different data, such that I can show you how to adapt the R Shiny app input to the users’ choices. For example, we’ll create a &lt;em&gt;DataType&lt;/em&gt; column that has value &lt;em&gt;Childlessness&lt;/em&gt; for the rows of the childlessness data and value &lt;em&gt;Gender Gap Index&lt;/em&gt; for all rows of the gender gap index data. We’ll also create a column &lt;em&gt;Period&lt;/em&gt; that contains earlier, middle and later periods for the childlessness data, and different years for the gender gap index data. As such, when the user chooses to explore the childlessness data, the input for the period will only contain the choices relevant to the childlessness data (i.e., earlier, middle, and later periods and no years). When the user chooses to explore the gender gap index data, they will only see different years as choices for the input of the period, and not earlier, middle, and later periods. The same goes for the &lt;em&gt;Indicator&lt;/em&gt; column. This may sound slightly vague at this point, but we’ll see this in practice later on when building the R Shiny app.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(reshape2)
childlessness_melt &amp;lt;- melt(childlessness_data, id = c(&amp;quot;Country&amp;quot;, &amp;quot;ISO3&amp;quot;, &amp;quot;Period&amp;quot;), 
                           variable.name = &amp;quot;Indicator&amp;quot;, value.name = &amp;quot;Value&amp;quot;)
childlessness_melt$Value &amp;lt;- as.numeric(childlessness_melt$Value)
gender_index_melt &amp;lt;- melt(gender_index_data, id = c(&amp;quot;ISO3&amp;quot;, &amp;quot;Country&amp;quot;, &amp;quot;Indicator&amp;quot;), 
                          variable.name = &amp;quot;Period&amp;quot;, value.name = &amp;quot;Value&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After melting the data and ensuring they’re in the same format, we merge them together using the &lt;code&gt;rbind()&lt;/code&gt; function, which we can do here because the data have the same column names.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;childlessness_melt[&amp;quot;DataType&amp;quot;] &amp;lt;- rep(&amp;quot;Childlessness&amp;quot;, nrow(childlessness_melt))
gender_index_melt[&amp;quot;DataType&amp;quot;] &amp;lt;- rep(&amp;quot;Gender Gap Index&amp;quot;, nrow(gender_index_melt))
df &amp;lt;- rbind(childlessness_melt, gender_index_melt)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;section-creating-an-interactive-world-map&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Creating an interactive world map&lt;/h2&gt;
&lt;p&gt;Next, it’s time to define the function that we’ll use for building our world maps. The inputs to this function are the merged data frame, the world data containing geographical coordinates, and the data type, period and indicator the user will select in the R Shiny app. We first define our own theme, &lt;code&gt;my_theme()&lt;/code&gt;, for setting the aesthetics of the plot. Next, we select only the data that the user has selected to view, resulting in &lt;em&gt;plotdf&lt;/em&gt;. We keep only the rows for which the ISO3 code has been specified (some countries, e.g., Channel Islands in the childlessness data, are not contained in the ISO code data). We then add the data the user wants to see to the geographical world data. Finally, we plot the world map. The most important part of this plot is that contained in the &lt;code&gt;geom_polygon_interactive()&lt;/code&gt; function from the &lt;code&gt;ggiraph&lt;/code&gt; package. This function draws the world map in white with grey lines, fills it up according to the value of the data selected (either childlessness or gender gap rank) in a red-to-blue color scheme set using the &lt;code&gt;brewer.pal()&lt;/code&gt; function from the &lt;code&gt;RColorBrewer&lt;/code&gt; package, and interactively shows in the tooltip the ISO3 code and value when hovering over the plot.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;worldMaps &amp;lt;- function(df, world_data, data_type, period, indicator){
  
  # Function for setting the aesthetics of the plot
  my_theme &amp;lt;- function () { 
    theme_bw() + theme(axis.text = element_text(size = 14),
                       axis.title = element_text(size = 14),
                       strip.text = element_text(size = 14),
                       panel.grid.major = element_blank(), 
                       panel.grid.minor = element_blank(),
                       panel.background = element_blank(), 
                       legend.position = &amp;quot;bottom&amp;quot;,
                       panel.border = element_blank(), 
                       strip.background = element_rect(fill = &amp;#39;white&amp;#39;, colour = &amp;#39;white&amp;#39;))
  }
  
  # Select only the data that the user has selected to view
  plotdf &amp;lt;- df[df$Indicator == indicator &amp;amp; df$DataType == data_type &amp;amp; df$Period == period,]
  plotdf &amp;lt;- plotdf[!is.na(plotdf$ISO3), ]
  
  # Add the data the user wants to see to the geographical world data
  world_data[&amp;#39;DataType&amp;#39;] &amp;lt;- rep(data_type, nrow(world_data))
  world_data[&amp;#39;Period&amp;#39;] &amp;lt;- rep(period, nrow(world_data))
  world_data[&amp;#39;Indicator&amp;#39;] &amp;lt;- rep(indicator, nrow(world_data))
  world_data[&amp;#39;Value&amp;#39;] &amp;lt;- plotdf$Value[match(world_data$ISO3, plotdf$ISO3)]
  
  # Create caption with the data source to show underneath the map
  capt &amp;lt;- paste0(&amp;quot;Source: &amp;quot;, ifelse(data_type == &amp;quot;Childlessness&amp;quot;, &amp;quot;United Nations&amp;quot; , &amp;quot;World Bank&amp;quot;))
  
  # Specify the plot for the world map
  library(RColorBrewer)
  library(ggiraph)
  g &amp;lt;- ggplot() + 
    geom_polygon_interactive(data = world_data, color = &amp;#39;gray70&amp;#39;, size = 0.1,
                                    aes(x = long, y = lat, fill = Value, group = group, 
                                        tooltip = sprintf(&amp;quot;%s&amp;lt;br/&amp;gt;%s&amp;quot;, ISO3, Value))) + 
    scale_fill_gradientn(colours = brewer.pal(5, &amp;quot;RdBu&amp;quot;), na.value = &amp;#39;white&amp;#39;) + 
    scale_y_continuous(limits = c(-60, 90), breaks = c()) + 
    scale_x_continuous(breaks = c()) + 
    labs(fill = data_type, color = data_type, title = NULL, x = NULL, y = NULL, caption = capt) + 
    my_theme()
  
  return(g)
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;section-building-an-r-shiny-app&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Building an R Shiny app&lt;/h2&gt;
&lt;p&gt;Now that we have our data and world mapping function ready and specified, we can start building our R Shiny app. (If you’re not familiar with R Shiny, I recommend that you to have a look at the &lt;a href=&#34;https://shiny.rstudio.com/tutorial/&#34;&gt;Getting Started guide&lt;/a&gt; first.) We can build our app by specifying the UI and server components. In the UI, we include a fixed user input selection where the user can choose whether they want to see the childlessness or gender gap index data. We further include dynamic inputs for the period and indicators the user wants to see. As mentioned before, these are dynamic because the choices shown will depend on the selections made by the user on previous inputs. We then use the &lt;code&gt;ggiraph&lt;/code&gt; package to output our interactive world map. We use the &lt;code&gt;sidebarLayout()&lt;/code&gt; function to show the input selections on the left side and the world map on the right side, rather than the two stacked vertically.&lt;/p&gt;
&lt;p&gt;Everything that depends on the inputs by the user needs to be specified in the server function, which in this case is not only the world map creation, but also the second and third input choices, since these depend on the previous inputs made by the user. For example, when we run the app later, we’ll see that when the user selects the childlessness data for the first input for data type, the third indicator input will only show age groups, and the text above the selector will also show “age group”, whereas when the user selects the gender gap index data, the third indicator will show different measures and the text above the selector will show “indicator” rather than “age group”.&lt;/p&gt;
&lt;p&gt;Finally, we can run our app by either clicking “Run App” in the top of our RStudio IDE, or by running&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;shinyApp(ui = ui, server = server)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Below is a screen shot of the app. You can check out the live app &lt;a href=&#34;https://fverkroost.shinyapps.io/interactive_worldmap_app/&#34;&gt;here&lt;/a&gt;. In &lt;a href=&#34;https://github.com/fverkroost/RStudio-Blogs/blob/master/interactive_worldmap_shiny_embedded.Rmd&#34;&gt;this&lt;/a&gt; post on my GitHub, you can also see how to embed a Shiny app in your R Markdown files, which is a really cool and innovative way of preparing interactive documents. Finally, the source code used to build the live app can also be found on my GitHub &lt;a href=&#34;https://github.com/fverkroost/RStudio-Blogs/blob/master/interactive_worldmap_shiny_app.R&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now try selecting different inputs and see how the input choices change when doing so. Also, don’t forget to try hovering over the world map to see different data values for different countries interactively!&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;interactive_worldmap_app.png&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2019/10/09/building-interactive-world-maps-in-shiny/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Onboard and Offboard Data Manipulation in Flexdashboard</title>
      <link>https://rviews.rstudio.com/2019/01/23/onboard-and-offboard-data-manipulation-in-flexdashboard/</link>
      <pubDate>Wed, 23 Jan 2019 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2019/01/23/onboard-and-offboard-data-manipulation-in-flexdashboard/</guid>
      <description>
        

&lt;p&gt;&lt;a href=&#34;https://csbaonline.org/about/people/staff/harrison-schramm&#34;&gt;Harrison Schramm&lt;/a&gt; is a Professional Statistician and Non-Resident Senior Fellow at the Center for Strategic and Budgetary Assessments.&lt;/p&gt;

&lt;p&gt;The Shiny set of tools, and, by extension, Flexdashboard, give professional analysts tools to rapidly put interactive versions of their work in the hands of clients.  Frequently, an end user will interact with data by either uploading or downloading a new set in its entirety (typically from a .csv or other similarly structured source), or do so ‘on the fly’ interactively, using tools like RHandsonTable.  What if you want to do both at the same time?  That is – what if you want to be able to change data interactively, or completely upload a new database &lt;em&gt;without stopping the current instance&lt;/em&gt;  or other ‘clunky’ things?&lt;/p&gt;

&lt;p&gt;It turns out that you can, and the implementation is relatively straightforward.  In this post, our aims are to:
a.  Make the reader more familiar with reactivity, particularly with respect to initializing and containerizing variables
b.  Show how to manage a single object that can be ‘touched’ by the uploadHandler and rHandsonTable
c.  Provide a worked example in Flexdashboard&lt;/p&gt;

&lt;p&gt;We need to create an environment where a data object that may be manipulated by functions inside an app is initialized to a pre-loaded set.  At runtime, the object may be downloaded to a .csv, manipulated directly in a spreadsheet-like interface, or replaced completely with an upload.&lt;/p&gt;

&lt;p&gt;In the following sections, we highlight the working parts of the minimal example (also provided) based on the attributes of different ships in Star Wars.&lt;/p&gt;

&lt;h2 id=&#34;step-1-initialization&#34;&gt;Step 1:  Initialization&lt;/h2&gt;

&lt;pre&gt;&lt;code class=&#34;language-r&#34;&gt;library(flexdashboard)
library(dplyr)
library(magrittr)
library(rhandsontable)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After calling the applicable libraries (above), we load a starter dataset so that the application isn’t empty when launched.  We also create a &lt;code&gt;reactiveValues&lt;/code&gt; object called &lt;code&gt;values&lt;/code&gt; that sets the handsontable &lt;code&gt;hot&lt;/code&gt; to NULL.  This is necessary because the handsontable object is self-referential in the sense that it is both an output and input device.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&#34;language-r&#34;&gt;BFL = read.csv(&amp;quot;StarterExampleData.csv&amp;quot;)
BFL$Exclude = FALSE
values &amp;lt;- reactiveValues(hot = NULL)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;main&lt;/strong&gt; trick is to hold the R dataframe in a reactive environment that responds to both the handsontable object and the upload handler.  This is done by a series of nested &lt;code&gt;if&lt;/code&gt; statements, that, in order, make the object equal:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the initialization file, if the object is empty (from the previous code chunk),&lt;/li&gt;
&lt;li&gt;the uploaded file (from the upload handler, below),&lt;/li&gt;
&lt;li&gt;and finally the handsontable object.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note the unglamorous statement &lt;code&gt;read.csv(input$InputBFL$datapath)&lt;/code&gt;.  This is necessary when reading a file provided by an upload handler.  Simply reading the handle attached to the csv will point to the &amp;lsquo;box&amp;rsquo;, not what is &amp;lsquo;in&amp;rsquo; the box.&lt;/p&gt;

&lt;p&gt;This is different than the approaches advocated on many forums where the initialization is done in the &lt;code&gt;rhandsontable&lt;/code&gt; code.  That approach is perfectly valid, but does not offer the flexibility of an uploaded file.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&#34;language-r&#34;&gt;BFLD = reactive({
  if(is.null(input$hot)){BFL}
  else if(!is.null(input$InputBFL)){read.csv(input$InputBFL$datapath)} 
  else{
  hot_to_r(input$hot)
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&#34;step-2-file-handlers&#34;&gt;Step 2: File Handlers&lt;/h2&gt;

&lt;p&gt;Now that we have set up the reactive structure for the object &lt;code&gt;BFLD&lt;/code&gt;, which can be accessed by other functions inside our code, we add the functionality for the upload and download handlers.&lt;/p&gt;

&lt;p&gt;The download function is two separate items: the &lt;code&gt;downloadButton&lt;/code&gt; that triggers the action, and the &lt;code&gt;downloadHandler&lt;/code&gt; that performs the interface.  In Shiny apps, the linkage is explicit.  In Flexdashboard, the linkage is made by putting the handler immediately after the button.  &lt;em&gt;Note:  The handlers do not always work in the RStudio App window; it may be necessary to &amp;lsquo;open in browser&amp;rsquo;&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&#34;language-r,&#34;&gt;downloadButton(&amp;quot;StarWarsDownload&amp;quot;, label = &amp;quot;Star Wars Download&amp;quot;)
downloadHandler(
  filename = function(){&amp;quot;Star_Wars_Download.csv&amp;quot;},
  content = function(file){
    write.csv(BFLD(), file)
  }
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The upload function is a single block.  Here the input File is linked to the reactive variable built in Step 1 by the handle &lt;code&gt;input$InputBFL&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&#34;language-r,&#34;&gt;fileInput(&amp;quot;InputBFL&amp;quot;, &amp;quot;Choose CSV File&amp;quot;,
                multiple = FALSE,
                accept = c(&amp;quot;text/csv&amp;quot;,
                         &amp;quot;text/comma-separated-values,text/plain&amp;quot;,
                         &amp;quot;.csv&amp;quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&#34;step-3-hands-on-table&#34;&gt;Step 3: Hands On Table&lt;/h2&gt;

&lt;p&gt;In the final step, we transform the stored reactive object &lt;code&gt;BFLD&lt;/code&gt; into a handsontable object, and output.  Note that because it is a reactive object, we call it as &lt;code&gt;BFLD()&lt;/code&gt; with parentheses, and inside a &amp;lsquo;render&amp;rsquo; context.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&#34;language-r,&#34;&gt;output$hot = renderRHandsontable({
  rhandsontable(BFLD(), height = 550) %&amp;gt;%  hot_rows()
})
rHandsontableOutput(&amp;quot;hot&amp;quot;) 
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;We hope that this minimal example will help you use both &lt;code&gt;rhandsontable&lt;/code&gt; and upload/download handlers in flexdashboard.  There should be enough code and explanations here for simpler cases.  These code chunks should help you worry less about IO handling in your applications and spend more time on graphics and analysis. Look &lt;a href=&#34;https://hschramm.shinyapps.io/UploadDownloadMinEx/&#34;&gt;here&lt;/a&gt; to see the example working.&lt;/p&gt;

&lt;p&gt;While we did not develop it here, it seems that this same construct could be used to add a web-based data source.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2019/01/23/onboard-and-offboard-data-manipulation-in-flexdashboard/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Communicating results with R Markdown</title>
      <link>https://rviews.rstudio.com/2018/11/01/r-markdown-a-better-approach/</link>
      <pubDate>Thu, 01 Nov 2018 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2018/11/01/r-markdown-a-better-approach/</guid>
      <description>
        


&lt;p&gt;&lt;img src=&#34;/post/2018-10-31-Stephens-Communicate_files/r4ds-com.png&#34; height = &#34;400&#34; width=&#34;600&#34;&gt;&lt;/p&gt;
&lt;p&gt;In my training as a consultant, I learned that long hours of analysis were typically followed by equally long hours of preparing for presentations. I had to turn my complex analyses into recommendations, and my success as a consultant depended on my ability to influence decision makers. I used a variety of tools to convey my insights, but over time I increasingly came to rely on &lt;a href=&#34;https://rmarkdown.rstudio.com/&#34;&gt;R Markdown&lt;/a&gt; as my tool of choice. R Markdown is easy to use, allows others to reproduce my work, and has powerful features such as parameterized inputs and multiple output formats. With R Markdown, I can share more work with less effort than I did with previous tools, making me a more effective data scientist. In this post, I want to examine three commonly used communication tools and show how R Markdown is often the better choice.&lt;/p&gt;
&lt;div id=&#34;microsoft-office&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Microsoft Office&lt;/h3&gt;
&lt;p&gt;The de facto tools for communication in the enterprise are still Microsoft Word, PowerPoint, and Excel. These tools, born in the 80’s and rising to prominence in the 90’s, are used everywhere for sharing reports, presentations, and dashboards. Although Microsoft Office documents are easy to share, they can be cumbersome for data scientists to write because they cannot be written with code. Additionally:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;They are not reproducible.&lt;/li&gt;
&lt;li&gt;They are separate from the code you used to create your analysis.&lt;/li&gt;
&lt;li&gt;They can be time-consuming to create and difficult to maintain.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In data science, your code - not your report or presentation - is the source of your results. Therefore, your documents should also be based on code! You can accomplish this with R Markdown, which produces documents that are generated by code, reproducible, and easy to maintain. Moreover, R Markdown documents can be rendered in &lt;a href=&#34;https://bookdown.org/yihui/rmarkdown/word-document.html&#34;&gt;Word&lt;/a&gt;, &lt;a href=&#34;https://bookdown.org/yihui/rmarkdown/powerpoint-presentation.html&#34;&gt;PowerPoint&lt;/a&gt;, and many other output formats. So, even if your client insists on having Microsoft documents, by generating them with R Markdown, you can spend more time working on your code and less time maintaining reports.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;r-scripts&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;R Scripts&lt;/h3&gt;
&lt;p&gt;Data science often involves interactive analyses with code, but code by itself is usually not enough to communicate results in an enterprise setting. In a &lt;a href=&#34;https://rviews.rstudio.com/2017/03/15/why-i-love-r-notebooks/&#34;&gt;previous post&lt;/a&gt;, I explained the benefits of using &lt;a href=&#34;https://bookdown.org/yihui/rmarkdown/notebook.html&#34;&gt;R Notebooks&lt;/a&gt; over R scripts for doing data science. An R Notebook is a special execution mode of R Markdown with two characteristics that make it very useful for communicating results:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Rendering a preview of an R Notebook does not execute R code, making it computationally convenient to create reports during or after interactive analyses.&lt;/li&gt;
&lt;li&gt;R Notebooks have an embedded copy of the source code, making it convenient for others to examine your work.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These two characteristics of R Notebooks combine the advantages of R scripts with the advantages of R Markdown. Like R scripts, you can do interactive data analyses and see all your code, but unlike R scripts you can easily create reports that explain why your code is important.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;shiny&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Shiny&lt;/h3&gt;
&lt;p&gt;Shiny and R Markdown are both used to communicate results. They both depend on R, generate high-quality output, and can be designed to accept user inputs. In previous posts, we discussed &lt;a href=&#34;https://rviews.rstudio.com/2017/09/20/dashboards-with-r-and-databases/&#34;&gt;Dashboards with Shiny&lt;/a&gt; and &lt;a href=&#34;https://rviews.rstudio.com/2018/05/16/replacing-excel-reports-with-r-markdown-and-shiny/&#34;&gt;Dashboards with R Markdown&lt;/a&gt;. Knowing when to use Shiny and when to use R Markdown will increase your ability to influence decision makers.&lt;/p&gt;
&lt;table style=&#34;width:44%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;20%&#34; /&gt;
&lt;col width=&#34;23%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;Shiny Apps&lt;/th&gt;
&lt;th&gt;R Markdown Documents&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Have an interactive and responsive user experience.&lt;/td&gt;
&lt;td&gt;Are snapshots in time, rendered in batch.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Are hosted on a web server that runs R.&lt;/td&gt;
&lt;td&gt;Have multiple output types such as HTML, Word, PDF, and many more.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Are not portable (i.e., users must visit the app).&lt;/td&gt;
&lt;td&gt;Are files that can be sent via email or otherwise shared.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Shiny is great – even “magical” – when you want your end users to have an interactive experience, but R Markdown documents are often simpler to program, easier to maintain, and can reach a wider audience. I use Shiny when I need an interactive user experience, but for everything else, I use R Markdown.&lt;/p&gt;
&lt;p&gt;If you need to accept user input, but you don’t require the reactive framework of Shiny, you can &lt;a href=&#34;https://bookdown.org/yihui/rmarkdown/parameterized-reports.html&#34;&gt;add parameters&lt;/a&gt; to your R Markdown code. This &lt;a href=&#34;https://resources.rstudio.com/rstudio-connect-2/parameterized-r-markdown-reports-with-rstudio-connect-aron-atkins&#34;&gt;process is easy and powerful&lt;/a&gt;, yet remains underutilized by most R users. It is a feature that would benefit a wide range of use cases, especially where the full power of Shiny is not required. Additionally, adding parameters to your document makes it easy to generate multiple versions of that document. If you host a document on &lt;a href=&#34;https://www.rstudio.com/products/connect/&#34;&gt;RStudio Connect&lt;/a&gt;, then users can select inputs and generate new versions on demand. Many Shiny applications today would be better suited as parameterized R Markdown documents.&lt;/p&gt;
&lt;p&gt;Finally, Shiny and R Markdown are not mutually exclusive. You can include Shiny elements in an R Markdown document, which enables you create a report that responds interactively to user inputs. These &lt;a href=&#34;https://bookdown.org/yihui/rmarkdown/shiny-documents.html&#34;&gt;Shiny documents&lt;/a&gt; are created with the simplicity of R markdown, but have the same hosting requirements of a Shiny app and are not portable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Summary&lt;/h3&gt;
&lt;p&gt;Using the right tools for communication matters. R Markdown is a better solution than conventional tools for the following problems:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;Problem&lt;/th&gt;
&lt;th&gt;Common tool&lt;/th&gt;
&lt;th&gt;Better tool&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Share reports and presentations&lt;/td&gt;
&lt;td&gt;Microsoft Office&lt;/td&gt;
&lt;td&gt;R Markdown&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Summarize and share your interactive analyses&lt;/td&gt;
&lt;td&gt;R Scripts&lt;/td&gt;
&lt;td&gt;R Notebooks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Update results (in batch) based on new inputs&lt;/td&gt;
&lt;td&gt;Shiny&lt;/td&gt;
&lt;td&gt;Parameterized reports&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;a href=&#34;http://r4ds.had.co.nz/index.html&#34;&gt;R For Data Science&lt;/a&gt; explains that, &lt;em&gt;“It doesn’t matter how great your analysis is unless you can explain it to others: you need to communicate your results.”&lt;/em&gt; I highly recommend reading &lt;a href=&#34;https://r4ds.had.co.nz/communicate-intro.html&#34;&gt;Part V&lt;/a&gt; of this book, which has chapters on using &lt;a href=&#34;https://r4ds.had.co.nz/r-markdown.html&#34;&gt;R Markdown&lt;/a&gt; as a unified authoring framework for data science, using &lt;a href=&#34;https://r4ds.had.co.nz/r-markdown-formats.html&#34;&gt;R Markdown formats&lt;/a&gt; for effective communication, and using &lt;a href=&#34;https://r4ds.had.co.nz/r-markdown-workflow.html&#34;&gt;R Markdown workflows&lt;/a&gt; to create analysis notebooks. There are references at the end of these chapters that describe where to learn more about communication.&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2018/11/01/r-markdown-a-better-approach/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Interactive plots in Shiny</title>
      <link>https://rviews.rstudio.com/2018/09/20/shiny-r2d3/</link>
      <pubDate>Thu, 20 Sep 2018 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2018/09/20/shiny-r2d3/</guid>
      <description>
        


&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2018-09-17-shiny-r2d3/header.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;I wish this post existed when I was struggling to add interactive plots to my Shiny app. I was mainly focused on recreating functionality found in other “dashboarding” applications. When looking for options, I found that &lt;a href=&#34;https://www.htmlwidgets.org/&#34;&gt;htmlwidgets&lt;/a&gt; were the closest to what companies usually expect. However, while they are great for client-side interactivity, I often hit walls with them when I try to add click-through interactivity because the functionality is either not there, is very limited, or is bloated. With &lt;code&gt;r2d3&lt;/code&gt; there is more work, but the gains in customization and interactivity make it by far the best choice, in my opinion.&lt;/p&gt;
&lt;p&gt;I asked a good friend at work to help me test the sample app provided in this post. She was able to run it easily, but then told me that she didn’t know that she was supposed to click on things. Adding interactive plots is one of the most important capabilities to include in a Shiny app. Sadly though, it seems that very few do it. If we wish to offer an alternative to enterprise reporting and BI tools by using Shiny, we need to do our best to match the interactivity those other tools seem to offer out of the box.&lt;/p&gt;
&lt;div id=&#34;the-sample-app&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;The sample app&lt;/h2&gt;
&lt;p&gt;I put together a sample app that should run in your R session by simply copying the code. This will allow us to focus on the details of the approach, and not on the setup.&lt;/p&gt;
&lt;p&gt;A working version of the app is available here: &lt;a href=&#34;https://beta.rstudioconnect.com/content/3940/&#34;&gt;Shiny-r2d3-app&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In this app, we can click on the bars and see the &lt;code&gt;DT&lt;/code&gt; object update based on the value of the bar. When the drop-down changes, the plot will update with a nice transition, as well.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;d3-is-hard&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;“D3 is hard”&lt;/h2&gt;
&lt;p&gt;The title is a quote of a luminary in the R community. A few months ago, I told him that I wanted to start using &lt;code&gt;r2d3&lt;/code&gt; but was struggling with making heads or tails of D3. This person has forgotten more than I will ever learn about pretty much any subject. If he says it’s hard, then I’m in for a world of hurt. Nevertheless, my naivete and stubbornness prevailed.&lt;/p&gt;
&lt;p&gt;I’ve since discovered that D3 is a language with which the desired result can be obtained by using one of several coding approaches. The more I learn to use it, the more I like its flexibility as a stand-alone visualization language.&lt;/p&gt;
&lt;p&gt;One thing that helped was to realize that D3 and &lt;code&gt;ggplot2&lt;/code&gt; are similar in the amount of flexibility they offer. Picture that what you are drawing for a bar plot are the actual rectangles, almost as if you’re using &lt;code&gt;geom_rect()&lt;/code&gt;. Except that in D3, the 0,0 coordinates are top/left, as opposed to bottom/left, so we have to flip our thinking upside down when we create a visualization with D3. In addition, the vertical and horizontal positions and sizes are expressed in fractions (read: percentages), so there are no absolute positions.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-good-way-to-start&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;A good way to start&lt;/h2&gt;
&lt;p&gt;After trying out several approaches, I think that a good way to start is by having a few “primer” D3 scripts that can be modified to suit a particular app.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;r2d3&lt;/code&gt; calls a D3 script with a &lt;code&gt;.js&lt;/code&gt; extension. As a result, the D3 code sits outside the R script, away from view. With &lt;code&gt;r2d3&lt;/code&gt;, a &lt;code&gt;data.frame&lt;/code&gt; can be used to pass all sorts of attributes (x/y coordinates, colors, etc.) to D3.&lt;/p&gt;
&lt;p&gt;A good way of thinking about these “primers” is that you are building your own &lt;code&gt;geom&lt;/code&gt;s as &lt;code&gt;.js&lt;/code&gt; scripts. So, once it’s done, you can pass the regular “right-side-up” coordinate data to &lt;code&gt;r2d3&lt;/code&gt; and it will know how to calculate the proper offsets to place the shapes in the correct spot.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-first-primer&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;A first primer&lt;/h2&gt;
&lt;p&gt;The idea in this section is to provide the smallest possible example that covers what I feel are the most important pieces that make up a presentable and functional product. My hope is that, if you find this interesting and useful for your line of work, you will take your time to dissect what each code section does, to learn the principles of this approach. This way, you can customize and even expand on the primer.&lt;/p&gt;
&lt;p&gt;The first example below is not the full primer. Instead, it is the section where most of the nuances of how the primer works exist. I’ll use that to explain some of the mechanics.&lt;/p&gt;
&lt;p&gt;You can copy-paste the following code in your R session and run it without worrying about file dependencies. I know how important that is when learning new things, so I’m using a small workaround to providing &lt;code&gt;r2d3&lt;/code&gt; a separate &lt;code&gt;.js&lt;/code&gt; file by saving the contents of a character variable that contains the D3 script into a temporary file. This is probably not something that you’ll do in a final Shiny app, but it works well for this example. Based on how the R Views’ code highlighter is setup, all of the D3 code will be in red, and the R code mostly in black:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(shiny)
library(dplyr)
library(r2d3)
library(forcats)

# D3 code inside an R character variable
r2d3_script &amp;lt;- &amp;quot;
// !preview r2d3 data= data.frame(y = 0.1, ylabel = &amp;#39;1%&amp;#39;, fill = &amp;#39;#E69F00&amp;#39;, mouseover = &amp;#39;green&amp;#39;, label = &amp;#39;one&amp;#39;, id = 1)
function svg_height() {return parseInt(svg.style(&amp;#39;height&amp;#39;))}
function svg_width()  {return parseInt(svg.style(&amp;#39;width&amp;#39;))}
function col_top()  {return svg_height() * 0.05; }
function col_left() {return svg_width()  * 0.20; }
function actual_max() {return d3.max(data, function (d) {return d.y; }); }
function col_width()  {return (svg_width() / actual_max()) * 0.55; }
function col_heigth() {return svg_height() / data.length * 0.95; }
var bars = svg.selectAll(&amp;#39;rect&amp;#39;).data(data);
bars.enter().append(&amp;#39;rect&amp;#39;)
    .attr(&amp;#39;x&amp;#39;,      col_left())
    .attr(&amp;#39;y&amp;#39;,      function(d, i) { return i * col_heigth() + col_top(); })
    .attr(&amp;#39;width&amp;#39;,  function(d) { return d.y * col_width(); })
    .attr(&amp;#39;height&amp;#39;, col_heigth() * 0.9)
    .attr(&amp;#39;fill&amp;#39;,   function(d) {return d.fill; })
    .attr(&amp;#39;id&amp;#39;,     function(d) {return (d.label); })
    .on(&amp;#39;click&amp;#39;, function(){
      Shiny.setInputValue(&amp;#39;bar_clicked&amp;#39;, d3.select(this).attr(&amp;#39;id&amp;#39;), {priority: &amp;#39;event&amp;#39;});
    })
    .on(&amp;#39;mouseover&amp;#39;, function(){
      d3.select(this).attr(&amp;#39;fill&amp;#39;, function(d) {return d.mouseover; });
    })
    .on(&amp;#39;mouseout&amp;#39;, function(){
      d3.select(this).attr(&amp;#39;fill&amp;#39;, function(d) {return d.fill; });
    });
&amp;quot;
# Save D3 code into a tempfile
r2d3_file &amp;lt;- tempfile()
writeLines(r2d3_script, r2d3_file)

# Shiny app starts here
ui &amp;lt;- fluidPage(
    d3Output(&amp;quot;d3&amp;quot;)
)

server &amp;lt;- function(input, output, session) {
    output$d3 &amp;lt;- renderD3({
        gss_cat %&amp;gt;%
            group_by(marital) %&amp;gt;%
            tally() %&amp;gt;%
            arrange(desc(n)) %&amp;gt;%
            mutate(
                y = n,
                ylabel = prettyNum(n, big.mark = &amp;quot;,&amp;quot;),
                fill = &amp;quot;#E69F00&amp;quot;,
                mouseover = &amp;quot;#0072B2&amp;quot;
            ) %&amp;gt;%
            r2d3(r2d3_file)
            # ^^ Use the temp file containing the D3 code
    })}

shinyApp(ui = ui, server = server)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The result should look like the screenshot below. In your R session, hovering over the bar will change the color. Also notice that the bars do not cover the entire window. This is because there are limits placed in the way of ratios within the functions used on the top of the script.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2018-09-17-shiny-r2d3/first.png&#34; /&gt;

&lt;/div&gt;
&lt;div id=&#34;code-breakdown&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Code breakdown&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;First, is the D3 code:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;I start by defining some canvas size function beginning with: &lt;code&gt;function svg_height() {return parseInt(svg.style(&#39;height&#39;))}&lt;/code&gt;. These allow for the correct relative placement and size, as well as adapting to a window resize. For example: &lt;code&gt;function actual_max() {return d3.max(data, function (d) {return d.y; }); }&lt;/code&gt; obtains the value of the longest bar, and then: &lt;code&gt;function col_width()  {return (svg_width() / actual_max()) * 0.55; }&lt;/code&gt; makes sure that the largest rectangle (representing a bar) drawn is 55% the size of the window. I used to define these as regular D3 variables, but found that as functions, they worked more consistently when running with Shiny.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;With &lt;code&gt;var bars = svg.selectAll(&#39;rect&#39;).data(data);&lt;/code&gt;, we create a new rectangle - better said, a new rectangle set. Just like with &lt;code&gt;geom_rect()&lt;/code&gt;, if you pass a vector with multiple values, it will create multiple rectangles. The last function, &lt;code&gt;data()&lt;/code&gt;, tells D3 to use the &lt;code&gt;data&lt;/code&gt; data set, which is the default name that &lt;code&gt;r2d3&lt;/code&gt; is using when it translates our &lt;code&gt;data.frame&lt;/code&gt; to a D3-friendly format. This is the “secret sauce” that allows us to use that data as attributes of the plot.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The rectangles are initially drawn with: &lt;code&gt;bars.enter().append(&#39;rect&#39;)&lt;/code&gt;. This will work fine as long as nothing changes. But with Shiny, we want change, so in a later section, I will introduce the &lt;code&gt;bars.transition()&lt;/code&gt; function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next, are the attributes (&lt;code&gt;.attr&lt;/code&gt;). Attributes are interesting in these kinds of objects. They are all named as a character variable (&lt;code&gt;x&lt;/code&gt;, &lt;code&gt;fill&lt;/code&gt;, etc.), so it’s essentially free-form. Each type of D3 shape has its own set of expected attributes, such as &lt;code&gt;x&lt;/code&gt;, &lt;code&gt;y&lt;/code&gt;, and &lt;code&gt;width&lt;/code&gt;, but I can also pass a “made-up” attribute and the script will not fail. In other words, if you pass an attribute of a “reserved” name for the shape. it will be used; for example, &lt;code&gt;r&lt;/code&gt; is the attribute for radius of a D3 circle. But if the attribute does not exist, it just becomes metadata that we can use later on if we want. This comes in handy if we want an ID field to be passed to Shiny, but that ID field is not displayed in the plot. The downside is that a misspelled attribute will fail silently, so it makes debugging a bit difficult. In other words, make sure that your attributes are spelled correctly! In the meantime, defining &lt;code&gt;x&lt;/code&gt; is easy because we want it to be as far to the left as possible.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Most attributes are set based on data passed via &lt;code&gt;r2d3&lt;/code&gt;. We do that by wrapping the value of the attribute inside a function. We already told D3 where the data comes from, so it is implied that in &lt;code&gt;function(d)&lt;/code&gt; the data object will be represented by &lt;code&gt;d&lt;/code&gt;. Another interesting thing about these functions is the second argument, usually represented by &lt;code&gt;i&lt;/code&gt;. It represents the “row number” of the observation. This means that a function like &lt;code&gt;function(d, i) { return d.x * i}&lt;/code&gt; will give the attribute the value of the &lt;code&gt;x&lt;/code&gt; variable of the &lt;code&gt;data.frame&lt;/code&gt; we passed to &lt;code&gt;r2d3&lt;/code&gt;, times the row number. So &lt;code&gt;.attr(&#39;fill&#39;,   function(d) {return d.fill; })&lt;/code&gt; simply passes the &lt;code&gt;fill&lt;/code&gt; value of our &lt;code&gt;data.frame&lt;/code&gt; to D3. Notice that we can name these fields whatever we want; we just need to map them appropriately. With a primer, I found that it’s better to keep either matching (or at the very least, generic) names so we can use them for other plots.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;on()&lt;/code&gt; functions track named events, such as &lt;code&gt;click&lt;/code&gt;, &lt;code&gt;mouseover&lt;/code&gt;, and &lt;code&gt;mouseout&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;click&lt;/code&gt; function will use a Shiny JavaScript function that makes the interaction possible. In &lt;code&gt;Shiny.setInputValue(&#39;bar_clicked&#39;, d3.select(this).attr(&#39;id&#39;), {priority: &#39;event&#39;});&lt;/code&gt;, I specify the name of the input inside Shiny, so &lt;code&gt;bar_clicked&lt;/code&gt; becomes &lt;code&gt;input$bar_clicked&lt;/code&gt; in R. The attribute &lt;code&gt;id&lt;/code&gt; is the value passed to R via that input. This is only a brief introduction to the topic; a much more detailed explanation with illustrations can be found in the &lt;a href=&#34;https://rstudio.github.io/r2d3/articles/shiny.html#d3-to-shiny&#34;&gt;&lt;code&gt;r2d3&lt;/code&gt; site&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;mouseover&lt;/code&gt; and &lt;code&gt;mouseout&lt;/code&gt; events are used to get the color-changing, hover-over effect. On &lt;code&gt;mouseover&lt;/code&gt;, the &lt;code&gt;fill&lt;/code&gt; attribute is updated to use the highlighting color and then restore it to the original color when the pointer leaves with &lt;code&gt;mouseout&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;For the R/Shiny code:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;As mentioned above, using &lt;code&gt;r2d3_file &amp;lt;- tempfile()&lt;/code&gt; and then &lt;code&gt;writeLines(r2d3_script, r2d3_file)&lt;/code&gt; is done to keep the D3 and R code in one location. This allows you to copy and run the script without worrying about dependencies.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;r2d3&lt;/code&gt; includes functions to interact with Shiny. The &lt;code&gt;d3Output()&lt;/code&gt; function is used in the &lt;code&gt;ui&lt;/code&gt; section of the app, and &lt;code&gt;renderD3()&lt;/code&gt; is used in the &lt;code&gt;server&lt;/code&gt; section of the app.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using &lt;code&gt;dplyr&lt;/code&gt;, the &lt;code&gt;forcats::gss_cat&lt;/code&gt; data is transformed to fit what the primer expects. In other words, the variable that the total count obtained with &lt;code&gt;tally()&lt;/code&gt; is renamed to &lt;code&gt;y&lt;/code&gt;. Additionally, new fields are added to specify the colors. A note about colors with D3: you can pass color names (“red”), or the Hex code of the color (“#E69F00”). Some additional tips for Hex color selection can be found in the &lt;a href=&#34;http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/#a-colorblind-friendly-palette&#34;&gt;&lt;code&gt;ggplot2&lt;/code&gt; cookbook&lt;/a&gt;. A very nice application to test different color schemes and explore contrast with different color deficiencies is &lt;a href=&#34;http://projects.susielu.com/viz-palette&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Thanks to the fact that the &lt;code&gt;r2d3()&lt;/code&gt; function uses the data as its first argument, we can simply pipe (&lt;code&gt;%&amp;gt;%&lt;/code&gt;) the &lt;code&gt;dplyr&lt;/code&gt; transformations directly to it. The only argument to pass to &lt;code&gt;r2d3()&lt;/code&gt; is the location of the new temporary file.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;the-full-example&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;The full example&lt;/h2&gt;
&lt;p&gt;Here is the full code for the sample app linked above. The D3 script is what I would consider a more complete “primer” that you can use in other apps. Copy and run the code to try out the Shiny app; as mentioned before, it should run without having to worry about any other file dependencies. More explanation and code breakdown is available after this code section:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(shiny)
library(dplyr)
library(r2d3)
library(forcats)
library(DT)
library(rlang)

r2d3_script &amp;lt;- &amp;quot;
// !preview r2d3 data= data.frame(y = 0.1, ylabel = &amp;#39;1%&amp;#39;, fill = &amp;#39;#E69F00&amp;#39;, mouseover = &amp;#39;green&amp;#39;, label = &amp;#39;one&amp;#39;, id = 1)
function svg_height() {return parseInt(svg.style(&amp;#39;height&amp;#39;))}
function svg_width()  {return parseInt(svg.style(&amp;#39;width&amp;#39;))}
function col_top()  {return svg_height() * 0.05; }
function col_left() {return svg_width()  * 0.20; }
function actual_max() {return d3.max(data, function (d) {return d.y; }); }
function col_width()  {return (svg_width() / actual_max()) * 0.55; }
function col_heigth() {return svg_height() / data.length * 0.95; }

var bars = svg.selectAll(&amp;#39;rect&amp;#39;).data(data);
bars.enter().append(&amp;#39;rect&amp;#39;)
    .attr(&amp;#39;x&amp;#39;,      col_left())
    .attr(&amp;#39;y&amp;#39;,      function(d, i) { return i * col_heigth() + col_top(); })
    .attr(&amp;#39;width&amp;#39;,  function(d) { return d.y * col_width(); })
    .attr(&amp;#39;height&amp;#39;, col_heigth() * 0.9)
    .attr(&amp;#39;fill&amp;#39;,   function(d) {return d.fill; })
    .attr(&amp;#39;id&amp;#39;,     function(d) {return (d.label); })
    .on(&amp;#39;click&amp;#39;, function(){
      Shiny.setInputValue(&amp;#39;bar_clicked&amp;#39;, d3.select(this).attr(&amp;#39;id&amp;#39;), {priority: &amp;#39;event&amp;#39;});
    })
    .on(&amp;#39;mouseover&amp;#39;, function(){
      d3.select(this).attr(&amp;#39;fill&amp;#39;, function(d) {return d.mouseover; });
    })
    .on(&amp;#39;mouseout&amp;#39;, function(){
      d3.select(this).attr(&amp;#39;fill&amp;#39;, function(d) {return d.fill; });
    });
bars.transition()
  .duration(500)
    .attr(&amp;#39;x&amp;#39;,      col_left())
    .attr(&amp;#39;y&amp;#39;,      function(d, i) { return i * col_heigth() + col_top(); })
    .attr(&amp;#39;width&amp;#39;,  function(d) { return d.y * col_width(); })
    .attr(&amp;#39;height&amp;#39;, col_heigth() * 0.9)
    .attr(&amp;#39;fill&amp;#39;,   function(d) {return d.fill; })
    .attr(&amp;#39;id&amp;#39;,     function(d) {return d.label; });
bars.exit().remove();

// Identity labels
var txt = svg.selectAll(&amp;#39;text&amp;#39;).data(data);
txt.enter().append(&amp;#39;text&amp;#39;)
    .attr(&amp;#39;x&amp;#39;, width * 0.01)
    .attr(&amp;#39;y&amp;#39;, function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
    .text(function(d) {return d.label; })
    .style(&amp;#39;font-family&amp;#39;, &amp;#39;sans-serif&amp;#39;);
txt.transition()
    .duration(1000)
    .attr(&amp;#39;x&amp;#39;, width * 0.01)
    .attr(&amp;#39;y&amp;#39;, function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
    .text(function(d) {return d.label; });
txt.exit().remove();

// Numeric labels
var totals = svg.selectAll().data(data);
totals.enter().append(&amp;#39;text&amp;#39;)
    .attr(&amp;#39;x&amp;#39;, function(d) { return ((d.y * col_width()) + col_left()) * 1.01; })
    .attr(&amp;#39;y&amp;#39;, function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
    .style(&amp;#39;font-family&amp;#39;, &amp;#39;sans-serif&amp;#39;)
    .text(function(d) {return d.ylabel; });
totals.transition()
    .duration(1000)
    .attr(&amp;#39;x&amp;#39;, function(d) { return ((d.y * col_width()) + col_left()) * 1.01; })
    .attr(&amp;#39;y&amp;#39;, function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
    .attr(&amp;#39;d&amp;#39;, function(d) { return d.x; })
    .text(function(d) {return d.ylabel; });
totals.exit().remove();
&amp;quot;
r2d3_file &amp;lt;- tempfile()
writeLines(r2d3_script, r2d3_file)

ui &amp;lt;- fluidPage(
  selectInput(&amp;quot;var&amp;quot;, &amp;quot;Variable&amp;quot;,
              list(&amp;quot;marital&amp;quot;, &amp;quot;rincome&amp;quot;, &amp;quot;partyid&amp;quot;, &amp;quot;relig&amp;quot;, &amp;quot;denom&amp;quot;),
              selected = &amp;quot;marital&amp;quot;),
  d3Output(&amp;quot;d3&amp;quot;),
  DT::dataTableOutput(&amp;quot;table&amp;quot;),
  textInput(&amp;quot;val&amp;quot;, &amp;quot;Value&amp;quot;, &amp;quot;Married&amp;quot;)
)

server &amp;lt;- function(input, output, session) {
  output$d3 &amp;lt;- renderD3({
    gss_cat %&amp;gt;%
      mutate(label = !!sym(input$var)) %&amp;gt;%
      group_by(label) %&amp;gt;%
      tally() %&amp;gt;%
      arrange(desc(n)) %&amp;gt;%
      mutate(
        y = n,
        ylabel = prettyNum(n, big.mark = &amp;quot;,&amp;quot;),
        fill = ifelse(label != input$val, &amp;quot;#E69F00&amp;quot;, &amp;quot;red&amp;quot;),
        mouseover = &amp;quot;#0072B2&amp;quot;
      ) %&amp;gt;%
      r2d3(r2d3_file)
  })
  observeEvent(input$bar_clicked, {
      updateTextInput(session, &amp;quot;val&amp;quot;, value = input$bar_clicked)
  })
  output$table &amp;lt;- renderDataTable({
    gss_cat %&amp;gt;%
      filter(!!sym(input$var) == input$val) %&amp;gt;%
      datatable()
  })
}

shinyApp(ui = ui, server = server)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;additions-to-d3-code&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Additions to D3 code&lt;/h3&gt;
&lt;p&gt;Hopefully, you can see a coding pattern emerging in the more lengthy example above. Here are some explanations for items that are new or outside the pattern:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;bars.transition()&lt;/code&gt; function “re-draws” the shape or text when the underlying data changes, when we make a change within the Shiny app. The &lt;code&gt;duration()&lt;/code&gt; function defines the time that the changes take. Be sure to copy all of the attributes from the &lt;code&gt;enter()&lt;/code&gt; function. This is needed when adding D3 plots into a Shiny app.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;var txt = svg.selectAll(&#39;text&#39;).data(data);&lt;/code&gt; code adds a new text object, similar to &lt;code&gt;geom_text()&lt;/code&gt;. The same coding pattern as the &lt;code&gt;rect&lt;/code&gt; shape applies. The additions are: a &lt;code&gt;text()&lt;/code&gt; function that defines what its displayed on screen (note that there’s no &lt;code&gt;attr(&#39;text&#39;,...&lt;/code&gt;), and the &lt;code&gt;style()&lt;/code&gt; function to allow setting the font type size.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;setting-up-the-shiny-interactivity&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Setting up the Shiny interactivity&lt;/h3&gt;
&lt;p&gt;There are three options to integrate the Shiny input created inside the D3 script:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;p&gt;Have a given Shiny &lt;code&gt;output&lt;/code&gt; react to the D3/Shiny input. An example would be to use it as a value to filter data in &lt;code&gt;filter(id_field == input$bar_clicked)&lt;/code&gt;. This works OK when there are not too many plots to integrate, but for a large dashboard, the second option would be better. An example of this approach can be found &lt;a href=&#34;https://rstudio.github.io/r2d3/articles/shiny.html#shiny-code&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use Shiny’s &lt;code&gt;observeEvent()&lt;/code&gt; to monitor the D3/Shiny input and have it run a specific action based on the value of the input. I usually use this approach to update another Shiny input in the app, and that is the approach used in this app.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use the &lt;code&gt;reactive()&lt;/code&gt; function to wrap all of the data transformations that are common across all of the plots inside the dashboard. Then have each plot use that function as the base of further &lt;code&gt;dplyr&lt;/code&gt; transformations. That approach can be found in the &lt;a href=&#34;http://db.rstudio.com/best-practices/dashboards/&#34;&gt;Enterprise Dashboards article&lt;/a&gt; on db.rstudio.com; here is &lt;a href=&#34;https://github.com/sol-eng/db-dashboard/blob/f3f42eabe722207510e6670ad81e36722e0b3d44/local_app.R#L91-L116&#34;&gt;a direct link to the code&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;other-r-additions&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Other R additions&lt;/h3&gt;
&lt;p&gt;A few additional tips that are helpful, but not mandatory:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;To get the effect of keeping the selected bar with a different color than the others, I used an &lt;code&gt;ifelse()&lt;/code&gt; inside the &lt;code&gt;mutate()&lt;/code&gt; that checks if a particular row matches to the selected &lt;code&gt;input&lt;/code&gt;: &lt;code&gt;fill = ifelse(label != input$val, &amp;quot;#E69F00&amp;quot;, &amp;quot;red&amp;quot;)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In this line: &lt;code&gt;mutate(label = !!sym(input$var))&lt;/code&gt;, I am using &lt;code&gt;rlang&lt;/code&gt;’s convention to allow for the plot to change the field that it is displaying. This is a very rare requirement in an app, so I hope that it doesn’t throw anyone off. This is an advanced R programming concept not necessary for D3/Shiny.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;I decided to use a separate field with the total count (&lt;code&gt;y&lt;/code&gt;) and the label that will be shown in that bar (&lt;code&gt;ylabel&lt;/code&gt;). It was easier for me to edit the format in R than in D3. Some may decide to do that in the D3 script.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;rstudio-1.2&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;RStudio 1.2&lt;/h2&gt;
&lt;p&gt;If you have the RStudio IDE Preview Release installed, you can easily preview the D3 visualization right in the Viewer pane. Information on how to do this is &lt;a href=&#34;https://rstudio.github.io/r2d3/#d3-preview&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In the first line in the script above, there is a D3 comment line with metadata that RStudio will pass to &lt;code&gt;r2d3&lt;/code&gt; so that you do not run R code in the console to see a preview. This integration also lets us use the IDE to edit the D3 file, which accelerates learning D3.&lt;/p&gt;
&lt;p&gt;To try this out with the visualization above, copy and paste the contents of the &lt;code&gt;r2d3_script&lt;/code&gt; variable to a new D3 file inside the RStudio IDE.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;closing-words&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Closing words&lt;/h2&gt;
&lt;p&gt;Thank you for making it this far! Even if you were just skimming, I hope one or two things I’ve shown were interesting enough to consider trying out the exercise.&lt;/p&gt;
&lt;p&gt;Sometimes, we forget how far we have progressed on a subject and forget what it feels like to begin the learning process. Hopefully these explanations avoid this pitfall and will simplify your learning experience. Please feel free to ask questions or start a topic of discussion at &lt;a href=&#34;https://community.rstudio.com/&#34;&gt;community.rstudio.com&lt;/a&gt;, where many are happy to help!&lt;/p&gt;
&lt;p&gt;Here are some additional links to resources that you may want to check out. The first two I wrote for RStudio documentation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://rstudio.github.io/r2d3/articles/shiny.html&#34;&gt;Using r2d3 with Shiny&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;http://db.rstudio.com/best-practices/dashboards/#using-r2d3-for-interactivity-and-drill-down&#34;&gt;Enterprise-ready dashboards&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;a href=&#34;https://github.com/d3/d3/blob/master/API.md&#34;&gt;D3 API reference&lt;/a&gt; is really good, I use it often.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;a href=&#34;https://rstudio.github.io/r2d3/&#34;&gt;&lt;code&gt;r2d3&lt;/code&gt; site&lt;/a&gt; has a great Gallery and articles to review. It has a section about &lt;a href=&#34;https://rstudio.github.io/r2d3/articles/learning_d3.html&#34;&gt;learning D3&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2018/09/20/shiny-r2d3/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>How to Build a Shiny &#34;Truck&#34;!</title>
      <link>https://rviews.rstudio.com/2018/09/04/how-to-build-shiny-trucks-not-shiny-cars/</link>
      <pubDate>Tue, 04 Sep 2018 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2018/09/04/how-to-build-shiny-trucks-not-shiny-cars/</guid>
      <description>
        


&lt;div id=&#34;why-is-this-about-trucks&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Why is this about trucks?&lt;/h2&gt;
&lt;p&gt;Last month, at the &lt;a href=&#34;https://www.rinpharma.com&#34;&gt;R/Pharma&lt;/a&gt; conference that took place on the Harvard Campus, I presented bioWARP, a large &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;Shiny&lt;/a&gt; application containing more than 500,000 lines of code. Although several other Shiny apps were presented at the conference, I noticed that none of them came close to being as big as bioWARP. And I asked myself, why?&lt;/p&gt;
&lt;p&gt;I concluded that most people just don’t need to build them that big! So now, I would like to explain why we needed such a large app and how we went about building it.&lt;/p&gt;
&lt;div style=&#34;width:45%;float:left;margin-right:5%&#34; align=&#34;justify&#34;&gt;
&lt;p&gt;To give you an idea of the scale I am talking about, an automotive metaphor might be useful. A typical Shiny app I see in my daily work has about 50 or even fewer interaction items. Let’s imagine this as a car. With less than 50 interactions, think of a small car like a Mini Cooper. Compared to these applications, with more than 500 interactions, bioWARP is a truck, maybe even a “monster” truck. So why do my customers want to drive trucks when everyone else is driving cars?&lt;/p&gt;
&lt;p&gt;Images by &lt;a href=&#34;https://flic.kr/p/B4TwtZ&#34;&gt;Paul V&lt;/a&gt; and &lt;a href=&#34;https://flic.kr/p/q33yzD&#34;&gt;DaveR&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div style=&#34;width:50%;float:left&#34;&gt;
&lt;a data-flickr-embed=&#34;true&#34;  href=&#34;https://www.flickr.com/photos/85090026@N06/23016489623/in/photolist-B4TwtZ-9AAG2n-ATVCE2-8H7BXs-bWEepB-b5oGq6-9ScLZx-nsQVXP-SwRfJn-p4pBSb-s8qk1A-RdvAzc-UTegWT-V5ik7W-nFDVyu-U4hhS5-S1YzQ4-TNJKtE-VMa34Q-dbBA7T-dxY87H-AUKEtM-BSURfW-R8PE1f-TxSqCy-Rn42kf-UWcGq3-ni1aoM-b5tFPc-cHPh5h-boLdCo-dm5ESK-9RCSui-aWp9Z8-8C8Ng3-9A1yQq-azvuBD-SsHkof-Tvu42W-RnbZWN-qHYHjN-of5Sks-BhCWbB-pqEKus-8CFqHD-aSwrqB-gcnXM8-dD4kxS-eNo35G-RuQVQa&#34; title=&#34;Peterbilt Truck&#34;&gt;&lt;img src=&#34;https://farm1.staticflickr.com/743/23016489623_736b8a0fe9_k.jpg&#34; width=&#34;47%&#34; alt=&#34;Peterbilt Truck&#34; style=&#34;float:left&#34;&gt;&lt;/a&gt;
&lt;script async src=&#34;//embedr.flickr.com/assets/client-code.js&#34; charset=&#34;utf-8&#34;&gt;&lt;/script&gt;
&lt;a data-flickr-embed=&#34;true&#34;  href=&#34;https://www.flickr.com/photos/paulsimpsonphotography/13976701169/in/photolist-ni5fjn-hEgG2w-dTbDzB-abjfn3-3taEfy-dLxzEr-5yi6v6-jsLLQY-83tFh7-n2RGZ-q33yzD-ajnH6q-ndAoYs-ejZRJ2-FWSHe-dT9v4V-8JBRm6-8JBMHn-ag2k7S-ggMQTe-8JBRUa-nuN77T-dVSEWm-poHbs9-ERMU7x-51keup-e87ZL9-6FMLjc-sbUX5C-eahQCz-cdeN9f-5YJau2-nGsU7-E2HYa-9YM6rR-5RfA6G-6FMQFi-5qSaux-9tMCaH-aTH7rc-5bk6Eq-6ndgG5-2Vj84C-h1SGnS-5gsVwN-m7CnAF-6UeYKd-32NNds-fzmfft-8kMdQ2&#34; title=&#34;Red Mini Cooper&#34;&gt;&lt;img src=&#34;https://farm3.staticflickr.com/2902/13976701169_cb0c28b2b3_z.jpg&#34; width=&#34;49%&#34; style=&#34;float:left&#34; alt=&#34;Red Mini Cooper&#34;&gt;&lt;/a&gt;
&lt;script async src=&#34;//embedr.flickr.com/assets/client-code.js&#34; charset=&#34;utf-8&#34;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;div style=&#34;clear:both&#34;&gt;

&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;why-do-we-need-a-truck&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Why do we need a truck?&lt;/h2&gt;
&lt;p&gt;Building software often starts with checking the user requirements. So when we started the development of our statistical web application, we did that, too. Asking a lot of people inside our department, we noticed that the list of requirements was huge:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Main user requirements&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Pretty design that works universally&lt;/li&gt;
&lt;li&gt;Interactive elements&lt;/li&gt;
&lt;li&gt;Mathematical correctness of all results&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Main application features&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Session logging&lt;/li&gt;
&lt;li&gt;Standardized PDF reports of all results&lt;/li&gt;
&lt;li&gt;Ability to restore sessions&lt;/li&gt;
&lt;li&gt;Harmonize it with other software applications&lt;/li&gt;
&lt;li&gt;Everything has to be tested&lt;/li&gt;
&lt;li&gt;Help pages&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;More requirements came then from all the analysis people perform on daily basis. They wanted to have some tasks integrated into our app:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Mathematical tasks&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Linear regression app&lt;/li&gt;
&lt;li&gt;Descriptive statistics app&lt;/li&gt;
&lt;li&gt;Homogeneity test app&lt;/li&gt;
&lt;li&gt;T-Test app&lt;/li&gt;
&lt;li&gt;Bootstrap simulation app&lt;/li&gt;
&lt;li&gt;Sensitivity/Specificity app&lt;/li&gt;
&lt;li&gt;Linearity app&lt;/li&gt;
&lt;li&gt;Clustering app&lt;/li&gt;
&lt;li&gt;BoxPlotting app&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Additionally, it was required to write the whole application in &lt;strong&gt;R&lt;/strong&gt;, as all our mathematical packages are written in &lt;strong&gt;R&lt;/strong&gt;. So we decided to do it all with &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;&lt;code&gt;shiny&lt;/code&gt;&lt;/a&gt; because it already covers two of the three main user requirements: being pretty and being interactive.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-did-we-build-the-truck&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;How did we build the truck?&lt;/h2&gt;
&lt;div id=&#34;modularity-standardization&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Modularity + Standardization&lt;/h3&gt;
&lt;p&gt;Inside our department, we were running some large-scale desktop applications already. When it came to testing, we always noticed that testing takes forever. If one single piece of software gathers data, calculates statistics, provides plot outputs, and renders PDF reports, this is a huge truck and you can just test it by driving it a thousand miles and see if it still works. The idea we came up with was building our truck out of Lego bricks. Each Lego brick can be tested on its own. If a Lego wheel runs, the truck will run. The wheel holder part is universal, and if we change the size of the wheels, we can still run the truck, assuming each wheel was tested. This is called modularity. There exist different solutions in R and &lt;code&gt;shiny&lt;/code&gt; that can be combined to make things modular:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Shiny Modules&lt;/li&gt;
&lt;li&gt;Object orientation&lt;/li&gt;
&lt;li&gt;R-packages&lt;/li&gt;
&lt;li&gt;Clever name-spacing&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As Shiny modules did not exist when we started, we chose options 2 and 3.&lt;/p&gt;
&lt;p&gt;As an example, I’ll compare two simple Shiny apps representing two cars here. One is written using object orientation; one is a simple Shiny application. The image below illustrates that the &lt;code&gt;renderPlot&lt;/code&gt; function in a standard Shiny app includes a plot, in this case using the &lt;code&gt;hist&lt;/code&gt; function. So whenever you add a new plot, its function has to be called inside.&lt;/p&gt;
&lt;p&gt;In the object-oriented app, the &lt;code&gt;renderPlot&lt;/code&gt; function calls the &lt;code&gt;shinyElement&lt;/code&gt; method of a generic plot object we created called &lt;code&gt;AnyPlot&lt;/code&gt;. The first advantage is that the plot can easily be exchanged. (Please look into the code if you wonder if this really is so.) To describe that advantage, you can imagine a normal car, built of car parts. Our car is really a a Lego car, using even smaller &lt;strong&gt;standardized&lt;/strong&gt; parts (Lego bricks) to construct each part of the car. So instead of the grille made of one piece of steel, we constructed it of many little grey Lego bricks. Changing the grille for an update of the car does not require us to reconstruct the whole front; just use green bricks instead of grey bricks, for example, since they should have the same shape.&lt;/p&gt;
&lt;p&gt;By going into the code of the two applications, you see there is a straight-forward disadvantage of object orientation: there is much more code. We have to define what a Lego brick is and what features it shall have.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2018-08-28-wolf-trucks_files/apps.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;&lt;a href=&#34;https://github.com/zappingseb/biowarptruck/blob/master/example_apps/app_object.R&#34;&gt;Object oriented shiny app&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(methods)
library(rlang)


setGeneric(&amp;quot;plotElement&amp;quot;,where = parent.frame(),def = function(object){standardGeneric(&amp;quot;plotElement&amp;quot;)})
setGeneric(&amp;quot;shinyElement&amp;quot;,where = parent.frame(),def = function(object){standardGeneric(&amp;quot;shinyElement&amp;quot;)})

setClass(&amp;quot;AnyPlot&amp;quot;, representation(plot_element = &amp;quot;call&amp;quot;))
setClass(&amp;quot;HistPlot&amp;quot;, representation(color=&amp;quot;character&amp;quot;,obs=&amp;quot;numeric&amp;quot;), contains = &amp;quot;AnyPlot&amp;quot;)

AnyPlot &amp;lt;- function(plot_element=expr(plot(1,1))){
  new(&amp;quot;AnyPlot&amp;quot;,
      plot_element = plot_element
  )
}

HistPlot &amp;lt;- function(color=&amp;quot;darkgrey&amp;quot;,obs=100){
  new(&amp;quot;HistPlot&amp;quot;,
      plot_element = expr(hist(rnorm(!!obs), col = !!color, border = &amp;#39;white&amp;#39;)),
      color = color,
      obs = obs
      )
}

#&amp;#39; Method to plot a Plot element
setMethod(&amp;quot;plotElement&amp;quot;,signature = &amp;quot;AnyPlot&amp;quot;,definition = function(object){
  eval(object@plot_element)
})
#&amp;#39; Method to render a Plot Element
setMethod(&amp;quot;shinyElement&amp;quot;,signature = &amp;quot;AnyPlot&amp;quot;,definition = function(object){
  renderPlot(plotElement(object))
})



server &amp;lt;- function(input, output, session) {

  # Create a reactive to create the Report object
  report_obj &amp;lt;- reactive(HistPlot(obs=input$obs))

  # Check for change of the slider to change the plots
  observeEvent(input$obs,{
    output$renderedPDF &amp;lt;- renderText(&amp;quot;&amp;quot;)
    output$renderPlot &amp;lt;-  shinyElement(  report_obj() )
  } )

}

# Simple shiny App containing the standard histogram + PDF render and Download button
ui &amp;lt;- fluidPage(
  sidebarLayout(
    sidebarPanel(
      sliderInput(
        &amp;quot;obs&amp;quot;,
        &amp;quot;Number of observations:&amp;quot;, min = 10, max = 500, value = 100)
    ),
    mainPanel(
      plotOutput(&amp;quot;renderPlot&amp;quot;)
    )
  )
)
shinyApp(ui = ui, server = server)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&#34;https://github.com/zappingseb/biowarptruck/blob/master/example_apps/app_stiff.R&#34;&gt;Standard shiny app&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;server &amp;lt;- function(input, output) {
  # Output Gray Histogram
  output$distPlot &amp;lt;- renderPlot({
    hist(rnorm(input$obs), col = &amp;#39;darkgray&amp;#39;, border = &amp;#39;white&amp;#39;)
  })

}

# Simple shiny App containing the standard histogram + PDF render and Download button
ui &amp;lt;- fluidPage(
  sidebarLayout(
    sidebarPanel(
      sliderInput(
            &amp;quot;obs&amp;quot;,
            &amp;quot;Number of observations:&amp;quot;, min = 10, max = 500, value = 100)
    ),
    mainPanel(
      plotOutput(&amp;quot;distPlot&amp;quot;)
    )
  )
)
shinyApp(ui = ui, server = server)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But an advantage of the object orientation is that you can now output the plot in a lot of different formats. We solved this by introducing methods called &lt;code&gt;pdfElement&lt;/code&gt;, &lt;code&gt;logElement&lt;/code&gt;, or &lt;code&gt;archiveElement&lt;/code&gt;. To get a deeper look, you can check out some examples stored on GitHub &lt;a href=&#34;https://github.com/zappingseb/biowarptruck/tree/master/example_apps&#34;&gt;here&lt;/a&gt;. These show differences between object-oriented and standard &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;&lt;code&gt;shiny&lt;/code&gt;&lt;/a&gt; apps. You can see that duplicated code is reduced in object-oriented apps, and while the code of the &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;&lt;code&gt;shiny&lt;/code&gt;&lt;/a&gt; app itself does not change for object-oriented apps, the code constructing the objects shown on the page changes. For the standard apps, the &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;&lt;code&gt;shiny&lt;/code&gt;&lt;/a&gt; code itself also changes every time an element is updated.&lt;/p&gt;
&lt;p&gt;The main advantage of this approach is that you can keep your &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;shiny&lt;/a&gt; app exactly the same whatever it calculates or whatever it reports. Inside our department, this meant that whenever somebody wants a different plot inside an app, we do not have to touch our main app again. Whenever somebody wanted to change just the linear regression app, we did not have to touch other apps. The look and feel, the logging, and the PDF report stays exactly the same. Those three features shall never be touched unless an update is needed to their own functionality.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;packaging&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Packaging&lt;/h3&gt;
&lt;p&gt;As you know, we did not build a singular app; we had to build many for the different mathematical analyses. So we decided that for each app we will construct a separate R package. This means we had to define one Class that defines what an app will look like in a &lt;em&gt;core&lt;/em&gt; package. This can be seen as fitting into the Lego theme. So our app would be Lego City, where you have trucks and cars. Other apps may be more advanced and range inside Lego Technic.&lt;/p&gt;
&lt;p&gt;Now each contributor to our &lt;code&gt;shiny&lt;/code&gt; app builds a package that contains a child of our &lt;em&gt;core&lt;/em&gt; class. We called this class &lt;strong&gt;Module&lt;/strong&gt;, and we have a lot of &lt;strong&gt;Module&lt;/strong&gt; packages. This is not a &lt;a href=&#34;https://shiny.rstudio.com/articles/modules.html&#34;&gt;Shiny module&lt;/a&gt;, but it’s modular. Our app now allows the bringing together a lot of those modules and making it bigger and bigger and bigger. It get’s more &lt;em&gt;HP&lt;/em&gt; and I wouldn’t call it a car anymore. Yeah, we have a truck! Made of Lego bricks!&lt;/p&gt;
&lt;a data-Flickr-embed=&#34;true&#34;  href=&#34;https://www.flickr.com/photos/157267479@N02/27368344058/in/photostream/&#34; title=&#34;truck peterbilt&#34;&gt;&lt;img src=&#34;https://farm1.staticflickr.com/807/27368344058_4d23c92951_o.png&#34; width=&#34;100%&#34; alt=&#34;truck peterbilt&#34;&gt;&lt;/a&gt;
&lt;script async src=&#34;//embedr.flickr.com/assets/client-code.js&#34; charset=&#34;utf-8&#34;&gt;&lt;/script&gt;
&lt;p&gt;&lt;a href=&#34;https://www.flickr.com/photos/157267479@N02/27368344058/in/photostream/&#34;&gt;Image by Barney Sharman&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The modularization and packaging now enables fast testing. Why? Each package can be tested using basic &lt;a href=&#34;https://github.com/r-lib/testthat&#34;&gt;testthat&lt;/a&gt; functions. So first we tested our &lt;em&gt;core&lt;/em&gt; application package, which allows adding building blocks. Afterwards, we tested each single package on its own. Finally, the whole application is tested. Our truck is ready to roll. Upon updates, we do not have to test the whole truck again. If we want to have larger tires, we just update the tire package, but not the &lt;em&gt;core&lt;/em&gt; package or any other packages.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;config-files&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Config files&lt;/h3&gt;
&lt;p&gt;The truck is made of bricks - actuallyn the same bricks we used to build the car, just many more of them. Now the hard part is putting them all together and not losing track.&lt;/p&gt;
&lt;p&gt;We are dealing with many the different &lt;strong&gt;Modules&lt;/strong&gt; that we were writing, each of which comes in its own package. The main issue we had was that we wanted all apps to be deeply tested. During development, of course, not all apps were tested right away, so we had to give them a tag (tested yes/no). Additionally, some apps required help pages while others don’t. Some apps came with example data sets; some don’t. Some apps had a nice title in them already; for some it shall be easy to configure. For each &lt;strong&gt;Module&lt;/strong&gt;, we’ll also have to source &lt;code&gt;js&lt;/code&gt; and &lt;code&gt;css&lt;/code&gt; files, which we allowed to be added for each app. The folder from which to source them shall be chosen by the app author. We wanted to provide as much flexibility as possible while keeping our standards for Lego bricks (look and feel, logging, plotting, and reporting). A simple example for such an app can be found on GitHub &lt;a href=&#34;https://github.com/zappingseb/biowarptruck/tree/master/example_packaged&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;We came up with the idea of config &lt;code&gt;XML&lt;/code&gt; files, which contain all the information needed to tell what needs to be set for each &lt;strong&gt;Module&lt;/strong&gt;. An example &lt;code&gt;XML&lt;/code&gt; document is given below, which you can read as the LEGO manual. These small configurations allow managing the apps. We also build an &lt;code&gt;XML&lt;/code&gt; document that allows the apps to use features of what we call &lt;em&gt;core&lt;/em&gt; package. This &lt;code&gt;XML&lt;/code&gt; file is rather difficult to set up, but imagine it tells which plot shall be logged, which input shall be used, and which plots shall go into the PDF report. It allows fast development while sticking to standards.&lt;/p&gt;
&lt;div style=&#34;clear:both&#34;&gt;

&lt;/div&gt;
&lt;div style=&#34;width:40%;margin-right:5%;float:left&#34;&gt;
&lt;a href=&#34;http://Lego.brickinstructions.com&#34; &gt;&lt;img src=&#34;https://i.imgur.com/nPzkkYd.png&#34; alt=&#34;drawing&#34; /&gt; &lt;br/&gt;from LegoBrickinstructions.com&lt;br/&gt;&lt;/a&gt;
&lt;/div&gt;
&lt;div style=&#34;float:left;width:49%&#34;&gt;
&lt;pre class=&#34;xml&#34;&gt;&lt;code&gt;&amp;lt;module id=&amp;quot;module1&amp;quot; type=&amp;quot;default&amp;quot; datasets=&amp;quot;yes&amp;quot; tested=&amp;quot;no&amp;quot;&amp;gt;
  &amp;lt;package&amp;gt; modulepackage1                  &amp;lt;/package&amp;gt;
  &amp;lt;class&amp;gt;   modulepackage1_Module           &amp;lt;/class&amp;gt;
  &amp;lt;title&amp;gt;   Great BoxPlot Module            &amp;lt;/title&amp;gt;
  &amp;lt;short&amp;gt;   GBM                             &amp;lt;/short&amp;gt;
  &amp;lt;path source=&amp;quot;modulepackage1&amp;quot;&amp;gt; .          &amp;lt;/path&amp;gt;
  &amp;lt;help&amp;gt;
    &amp;lt;level0&amp;gt;help/index.html&amp;lt;/level0&amp;gt;
    &amp;lt;level1&amp;gt;
        &amp;lt;item name=&amp;quot;details&amp;quot;&amp;gt;help/about.html&amp;lt;/item&amp;gt;
    &amp;lt;/level1&amp;gt;
  &amp;lt;/help&amp;gt;
  &amp;lt;data&amp;gt;
    &amp;lt;ds name=&amp;quot;Two Groups&amp;quot; file=&amp;quot;datasets/two_groups.csv&amp;quot;&amp;gt;
  &amp;lt;/data&amp;gt;
&amp;lt;/module&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div style=&#34;clear:both&#34;&gt;

&lt;/div&gt;
&lt;p&gt;Inside the config file, you can clearly see the title of the app and the location of help pages, and that an example data sets is given. Even the name of the class that describes the &lt;strong&gt;Module&lt;/strong&gt; is given. This allows us to rapidly add modules to our main app environment.&lt;/p&gt;
&lt;p&gt;At the end, our truck is made of many parts that all increase its power and strength. As we now have around 16 modules in our real (in production) app, and each has between 20 and 50 inputs, the truck has 500 inputs. All of them look similar and can be used to produced standardized PDF reports. The truck can even become a monster truck, and thanks to the config files, it will still be easy to manage.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;my-message-to-shiny.car-and-shiny.truck-developers&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;My message to shiny.car and shiny.truck developers&lt;/h2&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Please do not start building a car until you know how many parts it will have at the end. Always consider it might become a truck. At first, always define your requirements.&lt;/li&gt;
&lt;li&gt;Use modularization! Use &lt;a href=&#34;https://shiny.rstudio.com/articles/modules.html&#34;&gt;Shiny modules&lt;/a&gt; or inheritance provided by object orientation ( &lt;a href=&#34;http://adv-r.had.co.nz/S4.html&#34;&gt;s4&lt;/a&gt; or &lt;a href=&#34;https://cran.r-project.org/web/packages/R6/vignettes/Introduction.html&#34;&gt;s6&lt;/a&gt; ). Both keep you from changing a lot of code on minor changes in requirements.&lt;/li&gt;
&lt;li&gt;Use standardization! Try to have all your inputs and outputs as standardized as possible. If you use simple output bricks, it’s easy to output them in your preferred format. Features like logging, PDF reporting, or even testing will be much easier with standardized elements. Standardized inputs allow your users to be comfortable with new apps faster.&lt;/li&gt;
&lt;li&gt;Don’t build real trucks; build Lego trucks.&lt;/li&gt;
&lt;/ol&gt;
&lt;div style=&#34;width:100%;float:left&#34;&gt;
&lt;a data-flickr-embed=&#34;true&#34;  href=&#34;https://www.flickr.com/photos/85090026@N06/23016489623/in/photolist-B4TwtZ-9AAG2n-ATVCE2-8H7BXs-bWEepB-b5oGq6-9ScLZx-nsQVXP-SwRfJn-p4pBSb-s8qk1A-RdvAzc-UTegWT-V5ik7W-nFDVyu-U4hhS5-S1YzQ4-TNJKtE-VMa34Q-dbBA7T-dxY87H-AUKEtM-BSURfW-R8PE1f-TxSqCy-Rn42kf-UWcGq3-ni1aoM-b5tFPc-cHPh5h-boLdCo-dm5ESK-9RCSui-aWp9Z8-8C8Ng3-9A1yQq-azvuBD-SsHkof-Tvu42W-RnbZWN-qHYHjN-of5Sks-BhCWbB-pqEKus-8CFqHD-aSwrqB-gcnXM8-dD4kxS-eNo35G-RuQVQa&#34; title=&#34;Peterbilt Truck&#34;&gt;&lt;img src=&#34;https://farm1.staticflickr.com/743/23016489623_736b8a0fe9_k.jpg&#34; width=&#34;32%&#34; alt=&#34;Peterbilt Truck&#34; style=&#34;float:left;filter: sepia(2);&#34;&gt;&lt;/a&gt;
&lt;script async src=&#34;//embedr.flickr.com/assets/client-code.js&#34; charset=&#34;utf-8&#34;&gt;&lt;/script&gt;
&lt;a &gt;&lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/d/d7/Arrow_right.svg&#34; width=&#34;20%&#34; style=&#34;margin-left:5%;margin-right:5%;float:left;margin-top:100px&#34;&gt;&lt;/a&gt; &lt;a data-flickr-embed=&#34;true&#34;  href=&#34;https://www.flickr.com/photos/157267479@N02/27368344058/in/photostream/&#34; title=&#34;truck peterbilt&#34;&gt;&lt;img src=&#34;https://farm1.staticflickr.com/807/27368344058_4d23c92951_o.png&#34;  width=&#34;32%&#34; style=&#34;float:left&#34; alt=&#34;Red Mini Cooper&#34;&gt;&lt;/a&gt;
&lt;script async src=&#34;//embedr.flickr.com/assets/client-code.js&#34; charset=&#34;utf-8&#34;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;div style=&#34;clear:both&#34;&gt;

&lt;/div&gt;
&lt;p&gt;&lt;em&gt;Sebastian Wolf is a Biostatistician at Roche Diagnostics engaged in software, especially front-end development with a dedication to forming programmer communities.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The ideas and opinions expressed in this post are those of the author alone, and are not to be construed as representing the opinions of his employer or anyone else.&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2018/09/04/how-to-build-shiny-trucks-not-shiny-cars/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>JSM 2018 Itinerary</title>
      <link>https://rviews.rstudio.com/2018/07/25/jsm-2018-itinerary/</link>
      <pubDate>Wed, 25 Jul 2018 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2018/07/25/jsm-2018-itinerary/</guid>
      <description>
        


&lt;p&gt;JSM 2018 is almost here! Usually around this time, I comb through the entire program manually making an itinerary for myself. But this year I decided to try something new – a programmatic way of going through the program, and then building a Shiny app that helps me better navigate the online program.&lt;/p&gt;
&lt;p&gt;The end result of the app is below. (I might tweak it a bit further after this post goes live, depending on feedback I receive.) You can interact with the app &lt;a href=&#34;https://minecr.shinyapps.io/jsm2018-schedule/&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I’m often dissatisfied with conference webpages, and almost always dissatisfied with conference apps, so I thought this was a good opportunity to build one myself. Also, I’m teaching Shiny at JSM and have been wanting to acquaint myself better with the &lt;a href=&#34;http://glue.tidyverse.org/&#34;&gt;glue&lt;/a&gt; package, so I figured spending some time web scraping, text wrangling, and building an app could be fun. (Note to self: Next time do this &lt;em&gt;after&lt;/em&gt; you’re done preparing all your presentations!)&lt;/p&gt;
&lt;p&gt;This is a three part blog post: (1) the data, (2) the app, and (3) the itinerary.&lt;/p&gt;
&lt;p&gt;All relevant source code can be found &lt;a href=&#34;https://github.com/mine-cetinkaya-rundel/jsm2018-schedule&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;div id=&#34;the-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;The data&lt;/h2&gt;
&lt;p&gt;The data were scraped from the &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/index.cfm&#34;&gt;JSM 2018 Online Program&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Before scraping the data, I checked that the scraping is allowed on this page using &lt;code&gt;robotstxt::paths_allowed()&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(robotstxt)
paths_allowed(&amp;quot;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/index.cfm&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##
 ww2.amstat.org                      No encoding supplied: defaulting to UTF-8.&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looks like we’re good to go!&lt;/p&gt;
&lt;p&gt;Once you’re on the online program &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/index.cfm&#34;&gt;landing page&lt;/a&gt;, you need to click Search without setting any search parameters in order to get to a page with information on all JSM sessions. For convenience, I saved the resulting HTML file for this page in my repo. (You can access it &lt;a href=&#34;https://github.com/mine-cetinkaya-rundel/jsm2018-schedule/blob/master/data/jsm2018.html&#34;&gt;here&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;The next step is using &lt;a href=&#34;https://github.com/hadley/rvest&#34;&gt;rvest&lt;/a&gt; and the &lt;a href=&#34;https://selectorgadget.com/&#34;&gt;SelectorGadget&lt;/a&gt; to scrape the data. This process allows us to take not-so-tidy data from the web and turn it into a tidy data frame that we can then work with in R.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2018-07-25-jsm-2018-itinerary_files/data-scrape.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;Based on these data, I created two data frames: one for sessions and the other for talks. These two data frames will serve as the source data for the two tabs in the app. The code for data scraping the data and wrangling into these two data frames can be found &lt;a href=&#34;https://github.com/mine-cetinkaya-rundel/jsm2018-schedule/blob/master/scrape.R&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;the-app&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;The app&lt;/h2&gt;
&lt;p&gt;The app is built with Shiny, using a &lt;code&gt;navbarPage&lt;/code&gt; to allow for two separate &lt;code&gt;tabPanel&lt;/code&gt;s.&lt;/p&gt;
&lt;p&gt;The first panel is the session schedule. This tab allows users to subset sessions based on days and times, as well as session sponsors and types. This is similar to the functionality on the JSM page; however, it’s designed to easily subset for sessions I like having on my radar, and it allows me to subset by time of day.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2018-07-25-jsm-2018-itinerary_files/jsm2018-app-sessions.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;The second tab is designed to navigate talks, as opposed to sessions. You can look for keywords in talk titles. Curious how many talks have “R” in their title? How about “tidy”? Take a guess first, then peek at &lt;a href=&#34;https://minecr.shinyapps.io/jsm2018-schedule/&#34;&gt;the app&lt;/a&gt; to check your answer.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2018-07-25-jsm-2018-itinerary_files/jsm2018-app-talks.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;The source code for the app can be found &lt;a href=&#34;https://github.com/mine-cetinkaya-rundel/jsm2018-schedule/blob/master/app.R&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;the-itinerary&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;The itinerary&lt;/h2&gt;
&lt;p&gt;Using a combination of the app I build and good ol’ Ctrl-F on the online program, I came up with the following itinerary for JSM. The foci of the sessions I selected are education, data science, computing, visualization, and social responsibility. I obviously won’t make it to all the sessions I list here, but I plan to at least try to get my hands on the slides for the talks I don’t make.&lt;/p&gt;
&lt;p&gt;I also plan on stopping by the &lt;a href=&#34;https://ww2.amstat.org/meetings/jsm/2018/dataartshow.cfm&#34;&gt;JSM Data Art Show&lt;/a&gt; at some point!&lt;/p&gt;
&lt;p&gt;If you have suggestions for other sessions (in these topics or other) that you think should be on this list, let me know in the comments!&lt;/p&gt;
&lt;div id=&#34;saturday-jul-28&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Saturday, Jul 28&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;8:00 AM - 12:00 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215972&#34;&gt;Shiny Essentials&lt;/a&gt; - This morning I will be teaching a half-day workshop on building Shiny apps and dashboards. If you’re interested, you can sign up &lt;a href=&#34;https://www.amstat.org/_EventSolution/EventDisplay.aspx?WebsiteKey=26030f62-5b88-4f45-9fe5-e6cf2757ee09&amp;amp;Eventkey=JSM2018&amp;amp;e0fa4633_3294_4cc7_b5d8_eef47e46e6ea=2#e0fa4633_3294_4cc7_b5d8_eef47e46e6ea&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;8:00 AM - 4:00 PM: &lt;a href=&#34;https://sites.google.com/view/preparetoteach/&#34;&gt;Preparing Graduate Students to Teach Statistics and Data Science&lt;/a&gt; - This is a workshop designed to prepare graduate students for a role as undergraduate faculty responsible for teaching statistics and data science. I will be teaching two modules in this workshop in the afternoon.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;sunday-jul-29&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Sunday, Jul 29&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;2:00 PM - 3:50 PM
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215165&#34;&gt;Data Science Education - Successes and Challenges: Stories from the Classroom and Beyond&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215027&#34;&gt;Transparency, Reproducibility and Replicability in Work with Social and Economic Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215835&#34;&gt;Introductory Overview Lecture: The Deep Learning Revolution&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215591&#34;&gt;Leading to Quantitative Literacy&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;4:00 PM - 5:50 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215836&#34;&gt;Introductory Overview Lecture: Examining What and How We Teach at All Levels: Key Ideas to Ensure the Progress and Relevance of Statistics — Invited Special Presentation&lt;/a&gt; - I will be chairing this session and based on what I’ve seen from the fantastic speakers so far, I strongly recommend you not miss it!&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;monday-jul-30&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Monday, Jul 30&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;7:00 AM - 8:30 AM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=216530&#34;&gt;Section on Statistical Education Officers Meeting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;8:30 AM - 10:20 AM:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215215&#34;&gt;Visualization and Reproducibility - Challenges and Best Practices&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215677&#34;&gt;Curricular Considerations for Statistics and Data Science Education&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215837&#34;&gt;Introductory Overview Lecture: Leading Data Science: Talent, Strategy, and Impact&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;10:30 AM - 12:20 PM
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215256&#34;&gt;Creating and Sustaining an Undergraduate Research Program&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215482&#34;&gt;Statistical Computing and Statistical Graphics: Student Paper Award and Chambers Statistical Software Award&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215938&#34;&gt;SPEED: Teaching Statistics: Strategies and Applications&lt;/a&gt; (Ends at 11:15 AM)&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215941&#34;&gt;SPEED: Data Expo&lt;/a&gt; (Starts at 11:35 AM)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;2:00 PM - 3:50 PM: It will be particularly difficult to choose between these three sessions.
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215487&#34;&gt;Late-Breaking Session: Addressing Sexual Misconduct in the Statistics Community&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=214992&#34;&gt;An Emerging Ecosystem for Data Science/Statistics Education&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215035&#34;&gt;Academic Publication Is Dead, Long Live Academic Publication&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;4:00 PM - 5:50 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215427&#34;&gt;ASA President’s Invited Address - Helping to Save the Business of Journalism, One Data Insight at a Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;6:00 PM - 8:00 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=216569&#34;&gt;Statistical Computing and Statistics Graphics Mixer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;7:00 PM - 8:30 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=216813&#34;&gt;Public Lecture: Born on Friday the Thirteenth: The Curious World of Probabilities&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;tuesday-jul-31&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Tuesday, Jul 31&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;8:30 AM - 11:30 AM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=216546&#34;&gt;ASA DataFest Steering Committee and Information Session&lt;/a&gt; - If you’re running an ASA DataFest or if you’re interested running one next year, come join us! We’ll be discussing leads for next year’s dataset, and organization tips.&lt;/li&gt;
&lt;li&gt;8:30 AM - 10:20 AM:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215839&#34;&gt;Introductory Overview Lecture: Reproducibility, Efficient Workflows, and Rich Environments&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215319&#34;&gt;Student Outcomes in Undergraduate Courses Using a Simulation-Based Inference Approach to Teaching Statistics&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;10:30 AM - 12:20 PM:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215022&#34;&gt;The Future of Spatial and Spatio-Temporal Statistics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215286&#34;&gt;Graphics in Statistical Practice: Saying it with Pictures in the Classroom, Boardroom, or the Consulting Cube&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215809&#34;&gt;SPEED: Sports to Fire: Fascinating Applications of Statistics&lt;/a&gt; - A variety of interesting applications; there may be some good examples for teaching among them.&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215744&#34;&gt;Data Science&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215887&#34;&gt;Late-Breaking Session: Statistical Issues in Application of Machine Learning to High-Stakes Decisions&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;12:30 PM - 2:00 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=216815&#34;&gt;2019 SDSS Planning Meeting&lt;/a&gt; - I will be the short-course organizer for SDSS 2019. If you have ideas for a short course, either that you might want to teach or that you might want to take, let’s chat at JSM!&lt;/li&gt;
&lt;li&gt;2:00 PM - 3:50 PM:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215024&#34;&gt;Bringing Intro Stats into a Multivariate and Data-Rich World&lt;/a&gt; - I will be speaking at this session, hope to see you there!&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215580&#34;&gt;Lead with Statistics: Case Studies and Methods for Learning and Improving Healthcare Through EHRs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;5:30 PM - 7:30 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=216829&#34;&gt;Bayesian Mixer&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;wednesday-aug-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Wednesday, Aug 1&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;8:30 AM - 11:30 AM:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215099&#34;&gt;Getting Shots Inside the Box-Cox&lt;/a&gt; - I don’t usually go to sports statistics sessions, but (1) this one is about soccer and (2) that session title is pretty witty!&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215252&#34;&gt;Worldwide Statistics Without Borders Projects: Statistics, Data Visualization, and Decision Making&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215533&#34;&gt;Innovative and Effective Teaching for Large-Enrollment Statistics and Data Science Courses&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;10:30 AM - 12:20 PM:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215217&#34;&gt;The Potential for Web-Scraping in the Production of Official Statistics: An Opportunity for Statistics to Lead?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215333&#34;&gt;Cloud and Distributed Computing for Statisticians&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215674&#34;&gt;Fresh Approaches to Statistical Pedagogy&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;2:00 PM - 3:50 PM:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215679&#34;&gt;A Mixed Bag of Graphical Delights&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215089&#34;&gt;The State of Peer-Review and Publication in Statistics and the Sciences&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215131&#34;&gt;Innovations in Teaching Undergraduate Probability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215260&#34;&gt;Staying Statistically Relevant: Keep Your Skills Sharp!&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;4:00 PM - 5:50 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215426&#34;&gt;COPSS Awards and Fisher Lecture - The Future: Stratified Micro-Randomized Trials with Applications in Mobile Health&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;6:00 PM - 7:30 PM: &lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=216529&#34;&gt;Section on Statistical Education Business Meeting&lt;/a&gt; - Come celebrate the section turning 70, we’ll have cake!&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;thursday-aug-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Thursday, Aug 2&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;8:30 AM - 10:20 AM
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215033&#34;&gt;Foundation or Backdrop? - the Role of Statisticians in Academic Data Science Initiatives&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215525&#34;&gt;GAISEing into Introductory Service Courses in Light of Analytics/Data Scienc&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;10:30 AM - 12:20 PM
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215338&#34;&gt;Expanding the Tent: Undergraduate Majors in Data Science&lt;/a&gt; - I’ll be a discussant in this session, very much looking forward to hearing others’ ideas on curricular approaches for data science education.&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215026&#34;&gt;Data Science for Social Good&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215317&#34;&gt;The ‘Ergonomics’ of Statistics and Data Science&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://ww2.amstat.org/meetings/jsm/2018/onlineprogram/ActivityDetails.cfm?SessionID=215097&#34;&gt;Statistical Computing on Parallel Architectures&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2018/07/25/jsm-2018-itinerary/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Alternative Design for Shiny</title>
      <link>https://rviews.rstudio.com/2018/03/13/alternative-design-for-shiny/</link>
      <pubDate>Tue, 13 Mar 2018 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2018/03/13/alternative-design-for-shiny/</guid>
      <description>
        

&lt;h2 id=&#34;shiny-s-design&#34;&gt;Shiny&amp;rsquo;s Design&lt;/h2&gt;

&lt;p&gt;Most Shiny apps out there have a similar design style. It is usually easy for a seasoned Shiny developer to tell the difference between a Shiny app and a standard website. Why is this? Shiny apps ARE websites for all intents and purposes. Why do they not vary as greatly as the rest of the sites we encounter when surfing the web?&lt;/p&gt;

&lt;p&gt;This is partly due to the fact that many Shiny developers leverage pre-written code (e.g., the layout was presented to them). There is another major factor here, though: the web framework that powers Shiny, called &lt;strong&gt;Bootstrap&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&#34;bootstrap&#34;&gt;Bootstrap&lt;/h2&gt;

&lt;p&gt;Shiny implements the most widely used and established CSS, JavaScript, and HTML framework that exists today. Bootstrap was originally written for internal use at Twitter, and has since blossomed into the most utilized web framework across the web.&lt;/p&gt;

&lt;p&gt;People with experience in Shiny will recognize these examples (think &lt;code&gt;actionButton&lt;/code&gt; and &lt;code&gt;selectInput&lt;/code&gt;) from the Bootstrap website:&lt;/p&gt;

&lt;p&gt;&lt;img src=&#39;/post/2018-03-12-Anderson-Alternative-Design_files/bootstrap-buttons.png&#39; width=&#34;50%&#34;&gt;
&lt;img src=&#39;/post/2018-03-12-Anderson-Alternative-Design_files/bootstrap-select.png&#39; width=&#34;50%&#34;&gt;&lt;/p&gt;

&lt;h2 id=&#34;alternatives&#34;&gt;Alternatives&lt;/h2&gt;

&lt;p&gt;While Bootstrap is the most widely used web framework, other frameworks do exist that are also appealing. There are too many good ones to name here, so I will go directly to the one which is the basis for this article: &lt;strong&gt;Material Design&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&#34;material-design&#34;&gt;Material Design&lt;/h2&gt;

&lt;p&gt;Material Design is an extremely popular set of design standards created by Google. Anyone who uses Google web products (or Android) will quickly recognize some of their work.&lt;/p&gt;

&lt;p&gt;Here is an example of some UI elements that adhere to Material Design:&lt;/p&gt;

&lt;p&gt;&lt;img src=&#39;/post/2018-03-12-Anderson-Alternative-Design_files/material-design.png&#39; width=&#34;30%&#34;&gt;&lt;/p&gt;

&lt;h2 id=&#34;standards-vs-framework&#34;&gt;Standards vs. Framework&lt;/h2&gt;

&lt;p&gt;Material Design is not the same thing as Bootstrap. Bootstrap is the design standards, along with the CSS, JavaScript, and HTML code written to implement those standards. Material Design is only the standards. While Google has the resources to implement the standards themselves, for an average developer this would be extremely difficult to take on. Thankfully, open-source development has a solution: an excellent framework called &lt;strong&gt;Materialize CSS&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Materialize CSS implements Google&amp;rsquo;s Material Design with such precision that is indistinguishable from Google&amp;rsquo;s own implementation. The UI elements found in Materialize CSS are slick and are suitable for any web site or application.&lt;/p&gt;

&lt;h2 id=&#34;material-design-in-shiny&#34;&gt;Material Design in Shiny&lt;/h2&gt;

&lt;p&gt;Let&amp;rsquo;s assume someone wants to implement Material Design in a Shiny app. Where does one start? Yes, Materialize CSS exists, but that is code written for the web and not for native R users (hence Shiny). This leads to, yes, an R package. The package is called &lt;a target=&#34;_blank&#34; href =&#34;https://ericrayanderson.github.io/shinymaterial/&#34;&gt;&lt;code&gt;shinymaterial&lt;/code&gt;&lt;/a&gt;, and it allows Shiny developers to implement Material Design using only R code. The package contains many of the standard types of Shiny inputs, but with its own API (e.g., &lt;code&gt;material_select&lt;/code&gt; vs. &lt;code&gt;selectInput&lt;/code&gt;). Shiny developers will quickly pick up the similarities between &lt;code&gt;shinymaterial&lt;/code&gt; inputs and standard &lt;code&gt;shiny&lt;/code&gt; inputs.&lt;/p&gt;

&lt;p&gt;Along with inputs, the package also has more broad UI functionality, including the ability for Shiny developers to create Material dashboards, as shown &lt;a target=&#34;_blank&#34; href=&#34;https://ericrayanderson.shinyapps.io/shinymaterial_dashboard/&#34;&gt;here&lt;/a&gt;, along with other unique features such as parallax scrolling, shown &lt;a target=&#34;_blank&#34; href=&#34;https://ericrayanderson.shinyapps.io/shinymaterial_parallax/&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Shiny changed the game. It turned R programmers into web developers overnight. What &lt;a target=&#34;_blank&#34; href =&#34;https://ericrayanderson.github.io/shinymaterial/&#34;&gt;&lt;code&gt;shinymaterial&lt;/code&gt;&lt;/a&gt; aims to do is to provide Shiny developers with a little more design flexibility, while maintaining the spirit of Shiny: simple APIs that R developers can use to turn their scientific analyses into great web apps.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2018/03/13/alternative-design-for-shiny/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>The SeaClass R Package</title>
      <link>https://rviews.rstudio.com/2017/10/23/the-seaclass-r-package/</link>
      <pubDate>Mon, 23 Oct 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/10/23/the-seaclass-r-package/</guid>
      <description>
        


&lt;div id=&#34;the-seaclass-r-package&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;The SeaClass R Package&lt;/h1&gt;
&lt;p&gt;The Operations Technology and Advanced Analytics Group (OTAAG) at Seagate Technology has decided to share an internal project that helps accelerate development of classification models. The interactive SeaClass tool is contained in an R-based package built using &lt;code&gt;shiny&lt;/code&gt; and other CRAN packages commonly used for binary classification. The package is free to use and develop further, but any analysis mistakes are the sole responsibility of the user. Check out the demo video below:&lt;/p&gt;
&lt;p align=&#34;center&#34;&gt;
&lt;iframe width=&#34;95%&#34; height=&#34;480px&#34; src=&#34;https://www.youtube.com/embed/ZTz9ZcATQ_M&#34; frameborder=&#34;0&#34; allowfullscreen&gt;&lt;/iframe&gt;
&lt;/p&gt;
&lt;div id=&#34;origin-story&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Origin Story&lt;/h3&gt;
&lt;p&gt;Manufacturer data sets used for pass/fail analysis are typically highly imbalanced with many more passing cases than failing cases. In some situations, the failure examples may be scarce or nonexistent. In these extreme cases complex modeling techniques are likely inadvisable. Data scientists commonly consider data scarcity, class imbalance, and data dimensionality when discriminating between competing candidate approaches, such as anomaly detection, simple models, and complex models. Standard approaches are easily identified within each of these analysis categories, and can be exploited as reasonable initial classification analysis baselines.&lt;/p&gt;
&lt;p&gt;The SeaClass application was created to generate template R code for the commonly encountered classification problems described above. The application allows data analysts to explore multiple models quickly with essentially no programming required. SeaClass provides an option to download the corresponding R code for further model training/testing. This workflow enables our data analysts to jump-start their modeling, saving time and initial hassles.&lt;/p&gt;
&lt;p&gt;The Advanced Analytics group decided to open-source the package for several reasons. Firstly, we encourage other contributors to suggest improvements to the SeaClass application. Additionally, we are hopeful our application will inspire other code-generating projects within the R community. Lastly, our group benefits greatly from open-source tools, and it’s nice to give back every once in a while.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;package-overview&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Package Overview&lt;/h3&gt;
&lt;p&gt;The SeaClass R package provides tools for analyzing classification problems. In particular, specialized tools are available for addressing the problem of imbalanced data sets. The SeaClass application provides an easy-to-use interface that requires only minimal R programming knowledge to get started, and can be launched using the RStudio Addins menu. The application allows the user to explore numerous methods by simply clicking on the available options and interacting with the generated results. The user can choose to download the codes for any procedures they wish to explore further. SeaClass was designed to jump-start the analysis process for both novice and advanced R users. See screenshots below for one demonstration.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-10-16-Dienes-SeaClass_files/screen_shots.png&#34; /&gt;

&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;installation-instructions&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Installation Instructions&lt;/h3&gt;
&lt;p&gt;The SeaClass application depends on multiple R packages. To install SeaClass and its dependencies, run:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;install.packages(&amp;#39;devtools&amp;#39;)
devtools::install_github(&amp;#39;ChrisDienes/SeaClass&amp;#39;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;usage-instructions&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Usage Instructions&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt; Begin by loading and preparing your data in R. Some general advice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Your data set must be saved as an R data frame object.&lt;/li&gt;
&lt;li&gt;The data set must contain a binary response variable (0/1, PASS/FAIL, A/B, etc.)&lt;/li&gt;
&lt;li&gt;All other variables must be predictor variables.&lt;/li&gt;
&lt;li&gt;Predictor variables can be numeric, categorical, or factors.&lt;/li&gt;
&lt;li&gt;Including too many predictors may slow down the application and weaken performance.&lt;/li&gt;
&lt;li&gt;Categorical predictors are often ignored when the number of levels exceeds 10, since they tend to have improper influences.&lt;/li&gt;
&lt;li&gt;Missing values are not allowed and will throw a flag. Please remove or impute NAs prior to starting the app.&lt;/li&gt;
&lt;li&gt;Keep the number of observations (rows) to a medium or small size.&lt;/li&gt;
&lt;li&gt;Data sets with many rows (&amp;gt;10,000) or many columns (&amp;gt;30) may slow down the app’s interactive responses.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt; After data preparation, start the application by either loading SeaClass from the RStudio Addins drop-down menu, or by loading the SeaClass function from the command line. For example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(SeaClass)

### Make some fake data:
X &amp;lt;- matrix(rnorm(10000,0,1),ncol=10,nrow=1000)
X[1:100,1:2] &amp;lt;- X[1:100,1:2] + 3
Y &amp;lt;- c(rep(1,100), rep(0,900))
Fake_Data &amp;lt;- data.frame(Y = Y , X)

### Load the SeaClass rare failure data:
data(&amp;quot;rareFailData&amp;quot;)

### Start the interactive GUI:
SeaClass()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the application fails to load, you may need to specify your favorite browser path first. For example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;options(browser = &amp;quot;C:/Program Files (x86)/Google/Chrome/Application/chrome.exe&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt; The user has various options for configuring their analysis within the GUI. Once the analysis runs, the user can view the results, interact with the results (module-dependent), save the underlying R script, or start over. Additional help is provided within the application. See above screenshots for one depiction of these steps.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt; Besides the SeaClass function, several other functions are contained within the library. For example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;### List available functions:
ls(&amp;quot;package:SeaClass&amp;quot;)
### Note this is a sample data set:
# data(rareFailData)
### Note code_output is a support function for SeaClass, not for general use.

### View help:
?accuracy_threshold

### Run example from help file:
### General Use: ###
set.seed(123)
x &amp;lt;- c(rnorm(100,0,1),rnorm(100,2,1))
group &amp;lt;- c(rep(0,100),rep(2,100))
accuracy_threshold(x=x, group=group, pos_class=2)
accuracy_threshold(x=x, group=group, pos_class=0)
### Bagged Example ###
set.seed(123)
replicate_function = function(index){accuracy_threshold(x=x[index], group=group[index], pos_class=2)[[2]]}
sample_cuts &amp;lt;- replicate(100, {
  sample_index = sample.int(n=length(x),replace=TRUE)
  replicate_function(index=sample_index)
})
bagged_scores &amp;lt;- sapply(x, function(x) mean(x &amp;gt; sample_cuts))
unbagged_cut    &amp;lt;- accuracy_threshold(x=x, group=group, pos_class=2)[[2]]
unbagged_scores &amp;lt;- ifelse(x &amp;gt; unbagged_cut, 1, 0)
# Compare AUC:
PRROC::roc.curve(scores.class0 = bagged_scores,weights.class0 = ifelse(group==2,1,0))[[2]]
PRROC::roc.curve(scores.class0 = unbagged_scores,weights.class0 = ifelse(group==2,1,0))[[2]]
bagged_prediction &amp;lt;- ifelse(bagged_scores &amp;gt; 0.50, 2, 0)
unbagged_prediction &amp;lt;- ifelse(x &amp;gt; unbagged_cut, 2, 0)
# Compare Confusion Matrix:
table(bagged_prediction, group)
table(unbagged_prediction, group)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/10/23/the-seaclass-r-package/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Climate Change and Population Modeling in R</title>
      <link>https://rviews.rstudio.com/2017/10/09/population-modeling-in-r/</link>
      <pubDate>Mon, 09 Oct 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/10/09/population-modeling-in-r/</guid>
      <description>
        


&lt;p&gt;A recent paper in &lt;a href=&#34;https://www.nature.com/nclimate/&#34;&gt;nature climate change&lt;/a&gt;: &lt;a href=&#34;http://go.nature.com/2xiyNC0&#34;&gt;Less than 2°C warming by 2100 unlikely&lt;/a&gt; (Raftery et al. 2017), concludes that the goal of the &lt;a href=&#34;https://ec.europa.eu/clima/policies/international/negotiations/paris_en&#34;&gt;Paris Agreement&lt;/a&gt; is unlikely to be met.&lt;/p&gt;
&lt;p&gt;Although the conclusion is disheartening, the paper advances the science of climate modeling by developing a joint Bayesian hierarchical model for Gross Domestic Product per capita and carbon intensity. This ensemble of models, in turn, depends on the availability of probabilistic population projections developed by the &lt;a href=&#34;https://bayespop.csss.washington.edu/software/&#34;&gt;BayesPop&lt;/a&gt; Project at the University of Washington and available on CRAN.&lt;/p&gt;
&lt;p&gt;The linkage between CO&lt;sub&gt;2&lt;/sub&gt; emissions and population modeling comes through the use of a version of the &lt;a href=&#34;https://en.wikipedia.org/wiki/Kaya_identity&#34;&gt;Kaya identity&lt;/a&gt;, which “expresses future emissions levels in a country as a product of three components: population, GDP per capita, and carbon intensity (CO&lt;sub&gt;2&lt;/sub&gt; emissions per unit of GDP).”&lt;/p&gt;
&lt;p&gt;The 3700 lines of R code that implement the models underlying the paper are available &lt;a href=&#34;https://github.com/PPgp/Co2projections&#34;&gt;here&lt;/a&gt; on GitHub. Unless you work in this aspect of climate modeling, mastering this code seems likely to be a formidable task. A good first step, however, might be to work through the population models developed by BayesPop. These models comprise a series of R packages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://CRAN.R-project.org/package=bayesTFR&#34;&gt;&lt;code&gt;bayesTFR&lt;/code&gt;&lt;/a&gt; implements a Bayesian hierarchical model to make projections of total fertility for all of the countries in the world.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://cran.r-project.org/package=bayesLife&#34;&gt;&lt;code&gt;bayesLife&lt;/code&gt;&lt;/a&gt; implements a Bayesian Hierarchical model to make life expectancy projections for all the countries in the world is described &lt;a href=&#34;https://link.springer.com/article/10.1007%2Fs13524-012-0193-x&#34;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://cran.r-project.org/package=bayesPop&#34;&gt;&lt;code&gt;bayesPop&lt;/code&gt;&lt;/a&gt; uses &lt;code&gt;bayesTFR&lt;/code&gt; and &lt;code&gt;bayesLife&lt;/code&gt; to generate population projections for all of the world’s countries.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://cran.r-project.org/package=bayesDem&#34;&gt;&lt;code&gt;bayesDem&lt;/code&gt;&lt;/a&gt; provides graphical user interface for &lt;code&gt;bayesTFR&lt;/code&gt;, &lt;code&gt;bayesLife&lt;/code&gt; and &lt;code&gt;bayesPop&lt;/code&gt;.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://CRAN.R-project.org/package=wppExplorer&#34;&gt;&lt;code&gt;wppExployer&lt;/code&gt;&lt;/a&gt; implements a &lt;code&gt;shiny&lt;/code&gt; app for exploring the data in on the &lt;a href=&#34;https://esa.un.org/unpd/wpp/&#34;&gt;World Population Prospects&lt;/a&gt; This data is available in R packages &lt;a href=&#34;https://cran.r-project.org/package=wpp2017&#34;&gt;wpp2017&lt;/a&gt;, &lt;a href=&#34;https://cran.r-project.org/package=wpp2015&#34;&gt;wpp2015&lt;/a&gt;, &lt;a href=&#34;https://cran.r-project.org/package=wpp2012&#34;&gt;wpp2012&lt;/a&gt;, and &lt;a href=&#34;https://cran.r-project.org/package=wpp2010&#34;&gt;wpp2010&lt;/a&gt;,&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;code&gt;wppExployer&lt;/code&gt; &lt;code&gt;shiny&lt;/code&gt; app is also available &lt;a href=&#34;https://rstudio.stat.washington.edu/shiny/wppExplorer/inst/explore/&#34;&gt;online&lt;/a&gt;. &lt;br/&gt; &lt;iframe src = &#34;https://rstudio.stat.Washington.edu/shiny/wppExplorer/inst/explore/&#34; height = &#34;450&#34; width = &#34;100%&#34;&gt;&lt;/iframe&gt; &lt;br/&gt;&lt;/p&gt;
&lt;p&gt;To give you a feel for how these models work, we use the &lt;code&gt;bayesTFR&lt;/code&gt; package to estimate and plot fertility rates for the United States. (Note that, for brevity, the informative console output of the simulations in the code below have been suppressed.)&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(bayesTFR)
# This command produces output data, such as in the directory ex-data
sim.dir &amp;lt;- tempfile()
# Phase II MCMCs
m &amp;lt;- run.tfr.mcmc(nr.chains=1, iter=60, output.dir=sim.dir, seed=1, verbose=TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Loading required package: wpp2017&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Warning: package &amp;#39;wpp2017&amp;#39; was built under R version 3.4.2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Phase III MCMCs (not included in the package)
m3 &amp;lt;- run.tfr3.mcmc(sim.dir=sim.dir, nr.chains=2, iter=100, thin=1, seed=1, verbose=TRUE)
# Prediction
pred &amp;lt;- tfr.predict(m, burnin=30, burnin3=50, verbose=TRUE)
summary(pred, country=&amp;#39;United States of America&amp;#39;)
unlink(sim.dir, recursive=TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tfr.trajectories.plot(pred,country=&amp;quot;United States of America&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/post/2017-10-04-population-modeling-in-r_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;br/&gt;&lt;/p&gt;
&lt;p&gt;The transparent, reproducible work being done by Raftery and his collaborators, and the other members of the BayesPop Project, is a great gift to the R community. Anyone with an appetite for R code and the patience to learn something of Bayesian hierarchical models can gain some insight into one of the most important scientific problems of our day.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/10/09/population-modeling-in-r/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Enterprise-ready dashboards with Shiny and databases</title>
      <link>https://rviews.rstudio.com/2017/09/20/dashboards-with-r-and-databases/</link>
      <pubDate>Wed, 20 Sep 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/09/20/dashboards-with-r-and-databases/</guid>
      <description>
        


&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-09-12-dashboards-with-r-and-databases/main.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;Inside the enterprise, a dashboard is expected to have up-to-the-minute information, to have a fast response time despite the large amount of data that supports it, and to be available on any device. An end user may expect that clicking on a bar or column inside a plot will result in either a more detailed report, or a list of the actual records that make up that number. This article will cover how to use a set of R packages, along with Shiny, to meet those requirements.&lt;/p&gt;
&lt;div id=&#34;the-code&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;The code&lt;/h2&gt;
&lt;p&gt;A working example for the dashboard pictured above is available here: &lt;a href=&#34;https://edgarruiz.shinyapps.io/flights-dashboard/&#34;&gt;Flights Dashboard&lt;/a&gt;. The example has all of the functionality that is discussed in this article, except the database connectivity. The code for the dashboard is available in this Gist: &lt;a href=&#34;https://gist.github.com/edgararuiz/89e771b5d1b82adaa0033c0928d1846d&#34;&gt;app.R&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The code for the dashboard that actually connects to a database is available in this Gist: &lt;a href=&#34;https://gist.github.com/edgararuiz/876ba4718e56af66c3e1181482b6cb99&#34;&gt;app.R&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;begin-with-shinydashboard&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Begin with &lt;code&gt;shinydashboard&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&#34;https://rstudio.github.io/shinydashboard/&#34;&gt;shinydashboard&lt;/a&gt; package has three important advantages:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Provides an out-of-the-box framework to create dashboards in Shiny.&lt;/strong&gt; This saves a lot of time, because the developer does not have to create the dashboard features manually using “base” Shiny.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Has a dashboard-firendly tag structure.&lt;/strong&gt; This allows the developer to get started quickly. Inside the &lt;code&gt;dashboardPage()&lt;/code&gt;tag, the &lt;code&gt;dashboardHeader()&lt;/code&gt;, &lt;code&gt;dashboardSidebar()&lt;/code&gt; and &lt;code&gt;dashboardBody()&lt;/code&gt; can be added to easily lay out a new dashboard.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;It is mobile-ready.&lt;/strong&gt; Without any additional code, the dashboard layout will adapt to a smaller screen automatically.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;quick-example&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Quick example&lt;/h3&gt;
&lt;p&gt;If you are new to &lt;code&gt;shinydashboard&lt;/code&gt;, please feel free to copy and paste the following code to see a very simple dashboard in your environment:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(shinydashboard)
library(shiny)
ui &amp;lt;- dashboardPage(
  dashboardHeader(title = &amp;quot;Quick Example&amp;quot;),
  dashboardSidebar(textInput(&amp;quot;text&amp;quot;, &amp;quot;Text&amp;quot;)),
  dashboardBody(
    valueBox(100, &amp;quot;Basic example&amp;quot;),
    tableOutput(&amp;quot;mtcars&amp;quot;)
  )
)
server &amp;lt;- function(input, output) {
  output$mtcars &amp;lt;- renderTable(head(mtcars))
}
shinyApp(ui, server)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;deploy-using-config&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Deploy using &lt;code&gt;config&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;It is very common that credentials used during development will not be the same ones used for publishing. For databases, the best way to accommodate for this is to have a Data Source Name (DSN) with the same alias name set up on both environments. If it is not possible to set up DSNs, then the &lt;code&gt;config&lt;/code&gt; package can be used to make the switch between credentials used in the different environments invisible. The &lt;a href=&#34;http://docs.rstudio.com/connect/admin/process-management.html#using-the-config-package&#34;&gt;RStudio Connect&lt;/a&gt; product supports the use of the &lt;code&gt;config&lt;/code&gt; package out of the box. Another advantage of using &lt;code&gt;config&lt;/code&gt;, in lieu of Kerberos or DSN, is that the credentials used will not appear in the plain text of the R code. A more detailed write-up is available in the &lt;a href=&#34;http://db.rstudio.com/best-practices/portable-code&#34;&gt;Make scripts portable&lt;/a&gt; article.&lt;/p&gt;
&lt;p&gt;This code snippet is an example YAML file that &lt;code&gt;config&lt;/code&gt; is able to read. It has one driver name for local development, and a different name for use during deployment:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;default:
  mssql:
      Driver: &amp;quot;SQL Server&amp;quot;
      Server: &amp;quot;[server&amp;#39;s path]&amp;quot;
      Database: &amp;quot;[database name]&amp;quot;
      UID: &amp;quot;[user id]&amp;quot;
      PWD: &amp;quot;[pasword]&amp;quot;
      Port: 1433
rsconnect:
  mssql:
      Driver: &amp;quot;SQLServer&amp;quot;
      Server: &amp;quot;[server&amp;#39;s path]&amp;quot;
      Database: &amp;quot;[database name]&amp;quot;
      UID: &amp;quot;[user id]&amp;quot;
      PWD: &amp;quot;[pasword]&amp;quot;
      Port: 1433&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;default&lt;/code&gt; setting will be automatically used when development, and RStudio Connect will use the &lt;code&gt;rsconnect&lt;/code&gt; values when executing this code:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dw &amp;lt;- config::get(&amp;quot;mssql&amp;quot;)
con &amp;lt;- DBI::dbConnect(odbc::odbc(),
                      Driver = dw$Driver,
                      Server = dw$Server,
                      UID    = dw$UID,
                      PWD    = dw$PWD,
                      Port   = dw$Port,
                      Database = dw$Database)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;populate-shiny-inputs-using-purrr&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Populate Shiny inputs using &lt;code&gt;purrr&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;It is very common for Shiny inputs to retrieve their values from a table or a query. Because other queries in the dashboard will use the selected input to filter accordingly, the value required to pass to the other queries is normally an identification code, and not the label displayed in the drop down. To separate the keys from the values, the &lt;code&gt;map()&lt;/code&gt; function in the &lt;code&gt;purrr&lt;/code&gt; package can be used. In the example below, all of the records in the airlines table are collected, and a list of names is created, &lt;code&gt;map()&lt;/code&gt; is then used to insert the carrier codes into each name node.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# This code runs in ui
airline_list &amp;lt;- tbl(con, &amp;quot;airlines&amp;quot;) %&amp;gt;%
  collect  %&amp;gt;%
  split(.$name) %&amp;gt;%    # Place here the field that will be used for the labels
  map(~.$carrier)      # Place here the field that will be used for keys&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;selectInput()&lt;/code&gt; drop-down menu is able to read the resulting &lt;code&gt;airline_list&lt;/code&gt; list variable.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# This code runs in ui
 selectInput(
    inputId = &amp;quot;airline&amp;quot;,
    label = &amp;quot;Airline:&amp;quot;, 
    choices = airline_list) # Use airline_list as the choices argument value&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;take-advantage-of-dplyrs-laziness&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Take advantage of &lt;code&gt;dplyr&lt;/code&gt;’s “laziness”&lt;/h2&gt;
&lt;p&gt;Dashboards normally have a common data theme, which is sourced with a common data set. A base query can be built because &lt;code&gt;dplyr&lt;/code&gt; translates into SQL under the covers and, due to “laziness”, doesn’t evaluate the query until something is requested from it.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;db_flights &amp;lt;- tbl(con, &amp;quot;flights&amp;quot;) %&amp;gt;%
  left_join(tbl(con, &amp;quot;airlines&amp;quot;), by = &amp;quot;carrier&amp;quot;) %&amp;gt;%
  rename(airline = name) %&amp;gt;%
  left_join(tbl(con, &amp;quot;airports&amp;quot;), by = c(&amp;quot;origin&amp;quot; = &amp;quot;faa&amp;quot;)) %&amp;gt;%
  rename(origin_name = name) %&amp;gt;%
  select(-lat, -lon, -alt, -tz, -dst) %&amp;gt;%
  left_join(tbl(con, &amp;quot;airports&amp;quot;), by = c(&amp;quot;dest&amp;quot; = &amp;quot;faa&amp;quot;)) %&amp;gt;%
  rename(dest_name = name) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;dplyr&lt;/code&gt; variable can then be used in more than one Shiny output. A second example is in the code used to build the &lt;code&gt;highcharter&lt;/code&gt; plot below.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;output$total_flights &amp;lt;- renderValueBox({

  result &amp;lt;- db_flights %&amp;gt;%           # Use the db_flights variable
    filter(carrier == input$airline)
  if(input$month != 99) result &amp;lt;- filter(result, month == input$month)
  
  result &amp;lt;- result %&amp;gt;%
    tally %&amp;gt;%
    pull %&amp;gt;%                        # Use pull to get the total count as a vector
    as.integer()
  
  valueBox(value = prettyNum(result, big.mark = &amp;quot;,&amp;quot;),
           subtitle = &amp;quot;Number of Flights&amp;quot;)
})&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;drill-down&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Drill down&lt;/h2&gt;
&lt;p&gt;The idea of a “drill-down” action is that the end user is able to see part or all of the data that makes up the aggregate result displayed in the dashboard. A “drill-down” action has two parts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A dashboard element that displays a result is clicked. &lt;/strong&gt; The result is usually aggregate data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A new screen is displayed with another report.&lt;/strong&gt; The new report could be another report showing a lower-level aggregation, or it could show a list of rows that make up the result.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;a-dashboard-element-is-clicked&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A dashboard element is clicked&lt;/h3&gt;
&lt;p&gt;The following is one way that capturing a click event is possible. The idea is to display the top airport destinations for a given airline in a bar plot. When a bar is clicked, the desired result is for the plot to activate a drill-down. The &lt;code&gt;highcharter&lt;/code&gt; package will be used in this example.&lt;/p&gt;
&lt;p&gt;To capture a bar-click event in &lt;code&gt;highcharter&lt;/code&gt;, a small JavaScript needs to be written. The example below could be used in most cases, so you can copy and paste it as-is into your code. The variable name and the input name (&lt;code&gt;bar_clicked&lt;/code&gt;) would be the only two statements that would have to be changed to match your chart.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt; js_bar_clicked &amp;lt;- JS(&amp;quot;function(event) {Shiny.onInputChange(&amp;#39;bar_clicked&amp;#39;, [event.point.category]);}&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The command above creates a new JavaScript inside R that makes it possible to track when a bar is clicked. Here is a breakdown of the code:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;JS&lt;/strong&gt; - Indicates that the following function is JavaScript&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;function(event)&lt;/strong&gt; - Creates a new function, and expect an &lt;code&gt;event&lt;/code&gt; variable. The event that Highchart will pass is when a bar is clicked on, so the &lt;code&gt;event&lt;/code&gt; will contain information about that given bar.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shiny.onInputChange&lt;/strong&gt; - Is the function that JavaScript will use to interact with Shiny&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;bar_clicked&lt;/strong&gt; - Is the name of a new Shiny input; its value will default to the next item&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;[event.point.category]&lt;/strong&gt; - Passes the &lt;strong&gt;category&lt;/strong&gt; value of the &lt;strong&gt;point&lt;/strong&gt; where the click was made&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The next section will illustrate how to capture the change of the new &lt;code&gt;input$bar_clicked&lt;/code&gt;, and perform the second part of the “drill down”.&lt;/p&gt;
&lt;p&gt;In the &lt;code&gt;renderHighchart()&lt;/code&gt; output function, the variable that contains the JavaScript is passed as part of a list of events: &lt;code&gt;events = list(click = js_bar_clicked))&lt;/code&gt;. Because the event is inside the &lt;code&gt;hc_add_series()&lt;/code&gt; that creates the bar plot, then such click-event is tied to when the bar is clicked.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;output$top_airports &amp;lt;- renderHighchart({
  # Reuse the dplyr db_flights variable as the base query
  result &amp;lt;- db_flights %&amp;gt;%
    filter(carrier == input$airline) 
  if(input$month != 99) result &amp;lt;- filter(result, month == input$month) 
  result &amp;lt;- result %&amp;gt;
    group_by(dest_name) %&amp;gt;%
    tally() %&amp;gt;%
    arrange(desc(n)) %&amp;gt;%                          
    collect %&amp;gt;%
    head(10)                                      
  highchart() %&amp;gt;%
    hc_add_series(
      data = result$n, 
      type = &amp;quot;bar&amp;quot;,
      name = paste(&amp;quot;No. of Flights&amp;quot;),
      events = list(click = js_bar_clicked)) %&amp;gt;%   # The JavaScript variable is called here
    hc_xAxis(
      categories = result$dest_name,               # Value in event.point.category
        tickmarkPlacement=&amp;quot;on&amp;quot;)})&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;using-appendtab-to-create-the-drill-down-report&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Using &lt;code&gt;appendTab()&lt;/code&gt; to create the drill-down report&lt;/h3&gt;
&lt;p&gt;The plan is to display a new drill-down report every time the end user clicks on a bar. To prevent pulling the same data unnecessarily, the code will be smart enough to simply switch the focus to an existing tab if the same bar has been clicked on before.&lt;/p&gt;
&lt;p&gt;The new, and really cool, &lt;code&gt;appendTab()&lt;/code&gt; function is used to dynamically create a new Shiny tab with a &lt;strong&gt;DataTable&lt;/strong&gt; that contains the first 100 rows of the selection. A simple vector, called &lt;code&gt;tab_list&lt;/code&gt;, is used to track all existing detail tabs. The &lt;code&gt;updateTabsetPanel()&lt;/code&gt; function is used to switch to the newly or previously created tab.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;observeEvent()&lt;/code&gt; function is the one that “catches” the event executed by the JavaScript, because it monitors the &lt;code&gt;bar_clicked&lt;/code&gt; Shiny input. Comments are added to the code below to cover more aspects of how to use these features.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tab_list &amp;lt;- NULL

observeEvent(input$bar_clicked,{  
       airport &amp;lt;- input$bar_clicked[1]              # Selects the first value sent in [event.point.category]
       tab_title &amp;lt;- paste(input$airline,            # tab_title is the tab&amp;#39;s name and unique identifier
                          &amp;quot;-&amp;quot;, airport ,            
                          if(input$month != 99)     
                            paste(&amp;quot;-&amp;quot; , month.name[as.integer(input$month)]))
       
       if(tab_title %in% tab_list == FALSE){        # Checks to see if the title already exists
         details &amp;lt;- db_flights %&amp;gt;%                  # Reuses the db_flights dbplyr variable
           filter(dest_name == airport,             # Uses the [event.point.category] value for the filter
                  carrier == input$airline)         # Matches the current airline filter
         
         if(input$month != 99)                      # Matches the current month selection
            details &amp;lt;- filter(details, month == input$month) 
         details &amp;lt;- details %&amp;gt;%
           head(100) %&amp;gt;%                            # Select only the first 100 records
           collect()                                # Brings the 100 records into the R environment 
           
         appendTab(inputId = &amp;quot;tabs&amp;quot;,                # Starts a new Shiny tab inside the tabsetPanel named &amp;quot;tabs&amp;quot;
                   tabPanel(
                     tab_title,                     # Sets the name &amp;amp; ID
                     DT::renderDataTable(details)   # Renders the DataTable with the 100 newly collected rows
                   ))
         tab_list &amp;lt;&amp;lt;- c(tab_list, tab_title)        # Adds the new tab to the list, important to use &amp;lt;&amp;lt;- 
         }
         
       # Switches over to a panel that matched the name in tab_title.  
       # Notice that this function sits outside the if statement because
       # it still needs to run to select a previously created tab
       updateTabsetPanel(session, &amp;quot;tabs&amp;quot;, selected = tab_title)  
     })&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;remove-all-tabs-using-removetab-and-purrr&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Remove all tabs using &lt;code&gt;removeTab()&lt;/code&gt; and &lt;code&gt;purrr&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Creating new tabs dynamically can clutter the dashboard. So a simple &lt;code&gt;actionLink()&lt;/code&gt; button can be added to the &lt;code&gt;dashboardSidebar()&lt;/code&gt; in order to remove all tabs except the main dashboard tab.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# This code runs in ui
  dashboardSidebar(
       actionLink(&amp;quot;remove&amp;quot;, &amp;quot;Remove detail tabs&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;observeEvent()&lt;/code&gt; function is used once more to catch when the link is clicked. The &lt;code&gt;walk()&lt;/code&gt; command from &lt;code&gt;purrr&lt;/code&gt; is then used to iterate through each tab title in the &lt;code&gt;tab_list&lt;/code&gt; vector and proceeds to execute the Shiny &lt;code&gt;removeTab()&lt;/code&gt; command for each name. After that, the tab list variable is reset. Because of environment scoping, make sure to use double less than ( &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; ) when resetting the variable, so it knows to reset the variable defined outside of the &lt;code&gt;observeEvent()&lt;/code&gt; function.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# This code runs in server
  observeEvent(input$remove,{
    # Use purrr&amp;#39;s walk command to cycle through each
    # panel tabs and remove them
    tab_list %&amp;gt;%
      walk(~removeTab(&amp;quot;tabs&amp;quot;, .x))
    tab_list &amp;lt;&amp;lt;- NULL
  })
  &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;This example uses Shinydashboard to create enterprise dashboards, but there are other technologies as well. Flexdashboard is a great way to build similar enterprise dashboards in R Markdown. We used SQL Server to populate this dashboard, but you can use any database. For more information on using databases with R, see &lt;a href=&#34;http://db.rstudio.com/&#34; class=&#34;uri&#34;&gt;http://db.rstudio.com/&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/09/20/dashboards-with-r-and-databases/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Portfolio Volatility Shiny App</title>
      <link>https://rviews.rstudio.com/2017/08/09/portfolio-volatility-shiny-app/</link>
      <pubDate>Wed, 09 Aug 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/08/09/portfolio-volatility-shiny-app/</guid>
      <description>
        


&lt;p&gt;In our 3 previous posts, we walked through how to calculate &lt;a href=&#34;https://rviews.rstudio.com/2017/07/12/introduction-to-volatility/&#34;&gt;portfolio volatility&lt;/a&gt;, then how to calculate &lt;a href=&#34;https://rviews.rstudio.com/2017/07/18/introduction-to-rolling-volatility/&#34;&gt;rolling volatility&lt;/a&gt;, and then how to &lt;a href=&#34;https://rviews.rstudio.com/2017/07/21/visualizing-portfolio-volatility/&#34;&gt;visualize rolling volatility&lt;/a&gt;. Today, we will wrap all of that work into a Shiny app that allows a user to construct his or her own five-asset portfolio, choose a benchmark and a time period, and visualize the rolling volatilities over time.&lt;/p&gt;
&lt;p&gt;Here is the final app:&lt;/p&gt;
&lt;iframe src=&#34;https://jkr216.shinyapps.io/Portfolio-Volatility/&#34; width=&#34;100%&#34; ; height=&#34;700&#34;&gt;
&lt;/iframe&gt;
&lt;p&gt;There will be a slight departure in form today because we will use a &lt;code&gt;helpers.r&lt;/code&gt; file to hold our functions - those same functions that we worked so hard to create in the previous three posts. There are a few reasons to put them into a helper file.&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;p&gt;The end user won’t be able to see them, which leads to a tangent on the idea of reproducibility. We need to ask, “Reproducible by whom?”. In this case, the Shiny app is 100% reproducible by anyone who has access to that helper file, which would be my colleagues with access to my files or Github repository. But, if the end user is an external client, for example, that end user wouldn’t have access and the analytic functions would remain a black box. In the world of finance, that’s necessary most of the time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;From a workflow perspective, that helper file allows us to test those functions in different formats. I can create an R Markdown report that uses the file, test different Shiny apps, or tweak the functions themselves without having to alter the actual application code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;From a stylistic perspective, the helper file keeps the Shiny app code a bit cleaner and much shorter. It’s not right or wrong to use a helpers file, but it’s worth thinking about as our Shiny apps get more involved.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Here’s how we load that file and have access to the functions and objects in it:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;source(&amp;quot;function-folder/simple-vol-helpers.r&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Since this is a blog post and we want to be complete, the code chunk below contains all the code from that &lt;code&gt;simple-vol-helpers.r&lt;/code&gt; file.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Calculate component returns

componentReturns_df &amp;lt;- function(stock1, stock2, stock3, stock4, stock5, start_date){
  
  symbols &amp;lt;- c(stock1, stock2, stock3, stock4, stock5)
  
  prices &amp;lt;- 
    getSymbols(symbols, src = &amp;#39;yahoo&amp;#39;, from = start_date, 
               auto.assign = TRUE, warnings = FALSE) %&amp;gt;% 
    map(~Cl(get(.))) %&amp;gt;% 
    reduce(merge) %&amp;gt;%
    `colnames&amp;lt;-`(symbols)
  
  # generate daily return series for funds
  prices_monthly &amp;lt;- to.monthly(prices, indexAt = &amp;quot;first&amp;quot;, OHLC = FALSE)
  returns &amp;lt;- na.omit(ROC(prices_monthly, 1, type = &amp;quot;continuous&amp;quot;))
  
  
  returns_df &amp;lt;- returns %&amp;gt;% 
    as_tibble(preserve_row_names = TRUE) %&amp;gt;% 
    mutate(date = ymd(row.names)) %&amp;gt;% 
    select(-row.names) %&amp;gt;% 
    select(date, everything())
}


# Calculate rolling Portfolio Standard Deviation

rolling_portfolio_sd &amp;lt;- function(returns_df, start = 1, window = 6, weights){
  
  start_date &amp;lt;- returns_df$date[start]
  
  end_date &amp;lt;-  returns_df$date[c(start + window)]
  
  interval_to_use &amp;lt;- returns_df %&amp;gt;% filter(date &amp;gt;= start_date &amp;amp; date &amp;lt; end_date)
  
  returns_xts &amp;lt;- interval_to_use %&amp;gt;% as_xts(date_col = date) 
  
  w &amp;lt;- weights
  
  results_as_xts &amp;lt;- StdDev(returns_xts, weights = w, portfolio_method = &amp;quot;single&amp;quot;)
  results_as_xts &amp;lt;- round(results_as_xts, 4) * 100
  
  results_to_tibble &amp;lt;- as_tibble(t(results_as_xts[,1])) %&amp;gt;% 
    mutate(date = ymd(end_date)) %&amp;gt;% 
    select(date, everything()) 
  
}

# Look how long this code chunk is. Easier to stash this in a helpers.r file!&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All of those functions were explained and constructed in our previous Notebooks, so we won’t dwell on them today. Let’s move on to the appearance of the app itself!&lt;/p&gt;
&lt;p&gt;First, we need to create an input &lt;code&gt;sidebar&lt;/code&gt; where the user can choose assets, weights, a date, and a benchmark for comparison.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# This creates the sidebar input for the first stock and its weight.
# We&amp;#39;ll need to copy and paste this fluidRow for each of the assets in our portfolio. 
fluidRow(
  column(6,
  textInput(&amp;quot;stock1&amp;quot;, &amp;quot;Stock 1&amp;quot;, &amp;quot;SPY&amp;quot;)),
  column(4,
  numericInput(&amp;quot;w1&amp;quot;, &amp;quot;Portf. %&amp;quot;, 40, min = 1, max = 100))
)  

# Let the user choose a benchmark to compare to the portfolio volatility.
# We&amp;#39;ll default to the Russell 2000 small cap index.
textInput(&amp;quot;benchmark&amp;quot;, &amp;quot;Benchmark for Comparison&amp;quot;, &amp;quot;^RUT&amp;quot;)


fluidRow(
  column(6,
  dateInput(&amp;quot;start_date&amp;quot;, &amp;quot;Start Date&amp;quot;, value = &amp;quot;2013-01-01&amp;quot;)),
  column(3,
  numericInput(&amp;quot;window&amp;quot;, &amp;quot;Window&amp;quot;, 6, min = 3, max = 20, step = 1))
)

# This action button is important for user experience and server resources.
actionButton(&amp;quot;go&amp;quot;, &amp;quot;Submit&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That last line creates an &lt;code&gt;actionButton&lt;/code&gt;, which is important for the end user. We have more than 10 user inputs in that sidebar, and without that &lt;code&gt;actionButton&lt;/code&gt;, the app will start firing and reloading every time a user changes any of the inputs. This would be annoying for the user and taxing on the server! We will make sure the reactives wait for the user to click that button by using &lt;code&gt;eventReactive&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For example, in the lines below, the app will wait to calculate the rolling portfolio volatility because the value of &lt;code&gt;portfolio_rolling_vol&lt;/code&gt; is an &lt;code&gt;eventReactive&lt;/code&gt; that won’t fire until &lt;code&gt;input$go&lt;/code&gt; is true.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;portfolio_rolling_vol &amp;lt;- eventReactive(input$go, {
  
  returns_df &amp;lt;- 
    componentReturns_df(input$stock1, input$stock2, input$stock3, input$stock4, 
                        input$stock5, input$start_date) %&amp;gt;% 
    mutate(date = ymd(date))
  
  weights &amp;lt;- c(input$w1/100, input$w2/100, input$w3/100, input$w4/100, input$w5/100)
  
  window &amp;lt;- input$window
  
  roll_portfolio_result &amp;lt;-
    map_df(1:(nrow(returns_df) - window), rolling_portfolio_sd, 
         returns_df = returns_df, window = window, weights = weights) %&amp;gt;%
    mutate(date = ymd(date)) %&amp;gt;% 
    select(date, everything()) %&amp;gt;%
    as_xts(date_col = date) %&amp;gt;% 
    `colnames&amp;lt;-`(&amp;quot;Rolling Port SD&amp;quot;)
   # an xts comes out of this
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The user is going to choose a benchmark for comparison and we need another &lt;code&gt;eventReactive&lt;/code&gt; to take that input and calculate rolling volatility for the benchmark. The asset is passed via &lt;code&gt;input$benchmark&lt;/code&gt; from the sidebar.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;benchmark_rolling_vol &amp;lt;- eventReactive(input$go, {
  
  benchmark_prices &amp;lt;- 
    getSymbols(input$benchmark, src = &amp;#39;yahoo&amp;#39;, from = input$start_date, 
               auto.assign = TRUE, warnings = FALSE) 
  benchmark_close &amp;lt;- Cl(get(benchmark_prices))
    
  benchmark_prices_monthly &amp;lt;- to.monthly(benchmark_close, indexAt = &amp;quot;first&amp;quot;, OHLC = FALSE)
  benchmark_returns &amp;lt;- na.omit(ROC(benchmark_prices_monthly, 1, type = &amp;quot;continuous&amp;quot;))
  
  benchmark_rolling_sd &amp;lt;- rollapply(benchmark_returns,
                             input$window,
                             function(x) StdDev(x))
  benchmark_rolling_sd &amp;lt;- round(benchmark_rolling_sd, 4) * 100
  
  
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, when we visualize, it’s nice to include the chosen benchmark in the title. Thankfully, that is a simple &lt;code&gt;eventReactive&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;benchmark &amp;lt;- eventReactive(input$go, {input$benchmark})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We have now calculated three reactive objects: &lt;code&gt;portfolio_rolling_vol()&lt;/code&gt;, &lt;code&gt;benchmark_rolling_vol()&lt;/code&gt;, and &lt;code&gt;benchmark()&lt;/code&gt;. We pass them to &lt;code&gt;highcharter&lt;/code&gt; and tweak aesthetics on the y-axis.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;renderHighchart({
  highchart(type = &amp;quot;stock&amp;quot;) %&amp;gt;% 
    hc_title(text = paste(&amp;quot;Portfolio Volatility vs&amp;quot;, benchmark(), &amp;quot;Volatility&amp;quot;, sep = &amp;quot; &amp;quot;)) %&amp;gt;%
    hc_yAxis(title = list(text = &amp;quot;Vol Percent&amp;quot;),
           labels = list(format = &amp;quot;{value}%&amp;quot;),
           opposite = FALSE) %&amp;gt;% 
    hc_add_series(portfolio_rolling_vol(), name = &amp;quot;Portfolio Vol&amp;quot;, color = &amp;quot;blue&amp;quot;) %&amp;gt;%
    hc_add_series(benchmark_rolling_vol(), 
                  name = paste(benchmark(), &amp;quot;Vol&amp;quot;, sep = &amp;quot; &amp;quot;),
                  color = &amp;quot;green&amp;quot;) %&amp;gt;%
    hc_add_theme(hc_theme_flat()) %&amp;gt;%
    hc_navigator(enabled = FALSE) %&amp;gt;% 
    hc_scrollbar(enabled = FALSE)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We’ve presented nothing new of substance today, as those analytical functions were all built in previous posts. However, this app does allow the user to build a custom portfolio and compare to a benchmark of his or her choosing. Have fun with it, and try to find some assets whose volatility has been increasing since the election last November.&lt;/p&gt;
&lt;p&gt;Next time, we’ll take a closer look at the VIX and how it compares to realized volatility. Until then!&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/08/09/portfolio-volatility-shiny-app/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Printing From Flex Dashboard</title>
      <link>https://rviews.rstudio.com/2017/06/28/printing-from-flex-dashboard/</link>
      <pubDate>Wed, 28 Jun 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/06/28/printing-from-flex-dashboard/</guid>
      <description>
        


&lt;p&gt;Shiny applications of all stripes (including &lt;a href=&#34;http://rmarkdown.rstudio.com/flexdashboard/shiny.html&#34;&gt;flexdashboard with runtime Shiny&lt;/a&gt;) are revolutionary in that they put the power of R directly in the end user’s hands without needing to interact directly with the language. A common way end-users wish to interact with their data is via a dashboard that they can manipulate on the fly. &lt;a href=&#34;http://rmarkdown.rstudio.com/flexdashboard/&#34;&gt;Flexdashboard&lt;/a&gt; streamlines the process of turning an R-based analysis into a dashboard, so R users can create good-looking output for their analyses - and deploy this output to the web - with very little additional effort.&lt;/p&gt;
&lt;p&gt;There are various ways to extract information from flexdashboard, but no good way to programatically return a printable version of the &lt;em&gt;dashboard itself&lt;/em&gt;. This is partially by design - responsive HTML dashboards aren’t meant to be printed. There are &lt;a href=&#34;https://shiny.rstudio.com/articles/generating-reports.html&#34;&gt;well-documented workflows&lt;/a&gt; about how to share information between a web-centric output and a complementary report that renders to a printable format.&lt;/p&gt;
&lt;p&gt;That said, there are some reasons to want a printable output that looks similar to a related HTML report. Snapshots are valuable for documentation/training materials, for embedding in emails or other reports, or for the all-too-common case of meetings with executives who like dashboards but want to consume paper-based reports. Plus, flexdashboards are an incredibly quick way to create visually appealing &lt;em&gt;(read: pretty)&lt;/em&gt; summary output of a combination of outputs on a single page.&lt;/p&gt;
&lt;p&gt;Both Harrison and Aaron&lt;a href=&#34;#fn1&#34; class=&#34;footnoteRef&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; have struggled with trying to print flexdashboards in their respective practices. In a recent instance, Harrison was working with a client whose end users would be carrying snapshots of the dashboard into an industrial setting where mobile devices were not desired. It was important to the client to maintain a similar look between the on-screen and paper representations of the dashboard. It was also important to make generating these snapshots an integrated part of the application; it was not sufficient to suggest that the client manually take a screenshot of their browser window. This turned out to be a blessing, because (as you will see below) it allows the creation of a web-friendly ‘tabbed’ report with a companion ‘flat’ printed rendering.&lt;/p&gt;
&lt;div id=&#34;specific-task&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Specific Task&lt;/h3&gt;
&lt;p&gt;Our goal was to create a “printable” flexdashboard with runtime Shiny. Flexdashboard produces a beautiful HTML dashboard with very little effort. &lt;a href=&#34;https://shiny.rstudio.com/articles/interactive-docs.html&#34;&gt;Like all R Markdown documents&lt;/a&gt;, it also allows &lt;a href=&#34;https://shiny.rstudio.com/&#34;&gt;Shiny&lt;/a&gt; objects to be embedded inside of it, so that when rendered locally or on a server, it produces a reactive web application with minimal developer effort. Like many HTML files, however, it does not print well.&lt;/p&gt;
&lt;p&gt;The flexdashboard in question also had tabsets, which make perfect sense on a computer or mobile device, but don’t translate well to printed media. When printed, tabsets communicate that there is pertinent information hidden from the viewer; better to remove the tabset in the printed version. If the information is pertinent, it should be displayed in the printed document; if it is not, it should be removed.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;phantomjs-and-headless-chrome&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;PhantomJS and Headless Chrome&lt;/h3&gt;
&lt;p&gt;The approach we settled on as &lt;em&gt;good enough and easy enough&lt;/em&gt; was to use a &lt;a href=&#34;https://en.wikipedia.org/wiki/Headless_browser&#34;&gt;headless browser&lt;/a&gt; to take a screenshot of a non-reactive HTML document. It’s not a perfect solution: a PDF would be better than a png file, headless browsers add a code dependency, and there is some administrative overhead to create the document to print. It is, however, quick to implement, easy to understand, and robust.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;exampledownload&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Example&lt;a href=&#34;#fn2&#34; class=&#34;footnoteRef&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;The mechanics of building a screen-capture-style report from flexdashboard are neither difficult nor obvious. In general, it requires the following steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Add a downloadButton to a &lt;a href=&#34;http://rmarkdown.rstudio.com/flexdashboard/shiny.html&#34;&gt;flexdashboard with runtime Shiny&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;When the download button is invoked, temporarily save non-reactive copies of any objects of interest&lt;/li&gt;
&lt;li&gt;Knit a static HTML version of the flexdashboard, using the objects saved in the prior step&lt;/li&gt;
&lt;li&gt;Use &lt;a href=&#34;https://github.com/wch/webshot&#34;&gt;&lt;code&gt;webshot::webshot&lt;/code&gt;&lt;/a&gt; or &lt;a href=&#34;https://github.com/hrbrmstr/decapitated&#34;&gt;&lt;code&gt;decapitated::chrome_shot&lt;/code&gt;&lt;/a&gt; to capture a .png image of the static dashboard&lt;a href=&#34;#fn3&#34; class=&#34;footnoteRef&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Deliver this version to the client using the downloadHandler function&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The solution requires two separate R documents. The process is as follows:&lt;/p&gt;
&lt;div id=&#34;dynamic-flexdashboard-document&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Dynamic Flexdashboard document&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;
---
title: &#34;Snapshot Example&#34;
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: scroll
---
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is standard YAML header for a flexdashboard, including the command &lt;code&gt;runtime: shiny&lt;/code&gt; to create a Shiny application from an R Markdown document. Let’s examine the next chunks:&lt;/p&gt;
&lt;pre class=&#34;{r}&#34;&gt;&lt;code&gt;gears = mtcars$gear %&amp;gt;% as.factor() %&amp;gt;% levels()
selectizeInput(&amp;quot;grs&amp;quot;, &amp;quot;GEARS&amp;quot;,
               gears, selected = gears[1])
renderUI({
downloadButton(&amp;quot;downloadFile&amp;quot;, &amp;quot;Download&amp;quot;)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this chunk, we have built a &lt;code&gt;selectizeInput&lt;/code&gt; object to choose the number of gears to select, as well as a &lt;code&gt;downloadButton&lt;/code&gt; named ‘downloadFile’. Notice that we have wrapped the button in a &lt;code&gt;renderUI()&lt;/code&gt; context. This is standard shiny / flexdashboard code.&lt;/p&gt;
&lt;pre class=&#34;{r}&#34;&gt;&lt;code&gt;mpgp = reactive({
  mtcars %&amp;gt;% filter(gear %in% input$grs) %&amp;gt;% ggplot(aes(x = hp, y = mpg)) + geom_point() + geom_smooth()
  
})
renderPlot({
  mpgp()
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For veteran shiny programmers, this block may seem redundant. We’re creating a plot called &lt;code&gt;mpgp&lt;/code&gt; in a reactive context and then rendering it. In a ‘standard’ shiny implementation, we would simply have wrapped the plot code in the &lt;code&gt;renderPlot()&lt;/code&gt; context. However, as you will see below, we’re going to need to reuse the object &lt;code&gt;mpgp&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;{r}&#34;&gt;&lt;code&gt;output$downloadFile &amp;lt;- downloadHandler(filename = function() { 
return(paste(&amp;#39;Cars&amp;#39;, &amp;#39;.png&amp;#39;, sep=&amp;#39;&amp;#39;))
},
    content = function(file){
    to_save &amp;lt;- list(
    mpgg = mpgg(),
    mpgp = mpgp()
    )
      saveRDS(to_save, &amp;quot;config_data.RDS&amp;quot;)
      rmarkdown::render(&amp;quot;ShadowCars.Rmd&amp;quot;)
      webshot::webshot(&amp;quot;ShadowCars.html&amp;quot;, file = file)
                        })&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This chunk contains the secret sauce. When the &lt;code&gt;downloadButton&lt;/code&gt; is invoked, the program saves all elements to appear in the downloaded report in a file called ‘config_data.RDS’. These elements are then used as arguments to render a shadow document, ‘ShadowCars.Rmd’. Finally, &lt;code&gt;webshot::webshot&lt;/code&gt; converts the hidden document to a .png and delivers it to the client side.&lt;/p&gt;
&lt;p&gt;The full dashboard looks like this:&lt;/p&gt;
&lt;!-- ![*Screenshot of our minimal implementation of a flexdashboard with downloadable screenshot*](/post/2017-06-19-Printing-From-Flex-Dashboard_files/MinDWN.png) --&gt;

&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-06-19-Printing-From-Flex-Dashboard_files/MinDWN.png&#34; /&gt;

&lt;/div&gt;

&lt;/div&gt;
&lt;div id=&#34;shadow-document&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Shadow Document&lt;/h4&gt;
&lt;p&gt;The key elements of the shadow document code are presented below:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;---
title: &amp;quot;Snapshot Example&amp;quot;
output:
  flexdashboard::flex_dashboard:
    orientation: rows
---&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that our YAML for the shadow document is similar to the dashboard, except it does &lt;strong&gt;not&lt;/strong&gt; include &lt;code&gt;runtime: shiny&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The code blocks that render the objects created in the dynamic document are straightforward to the point of triviality; they simply reference the saved objects (which are retrieved using &lt;code&gt;readRDS&lt;/code&gt;) and render them using whatever we choose, in this case &lt;code&gt;kable()&lt;/code&gt; for the table and the native &lt;code&gt;print()&lt;/code&gt; for the plot.&lt;/p&gt;
&lt;pre class=&#34;{r}&#34;&gt;&lt;code&gt;data &amp;lt;- readRDS(&amp;quot;config_data.RDS&amp;quot;)
data$mpgg %&amp;gt;% kable() &lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;{r}&#34;&gt;&lt;code&gt;data$mpgp %&amp;gt;% print() &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And of course, while &lt;code&gt;mpgp&lt;/code&gt; was reactive in the original dashboard, it is static in the shadow doc.&lt;/p&gt;
&lt;p&gt;The report delivered to the client is as follows:&lt;/p&gt;
&lt;!-- ![*Example of the type of report delivered to the client in png format.  Note that while the report contains the same objects as the dynamic page, the chart and graph are laid side-by-side, not tabset*](/post/2017-06-19-Printing-From-Flex-Dashboard_files/Cars.png) --&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-06-19-Printing-From-Flex-Dashboard_files/Cars.png&#34; /&gt;

&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In this short post, we have shown how to create a downloadable custom report by using existing tools to create a static flexdashboard. From the .png environment, the rendered image can be converted to other formats as required.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;&lt;a href=&#34;https://www.linkedin.com/in/harrisonschramm&#34;&gt;Harrison Schramm&lt;/a&gt; is an Operations Research Analyst at &lt;a href=&#34;http://www.canallc.com/&#34;&gt;CANA Advisors&lt;/a&gt;. &lt;a href=&#34;https://www.linkedin.com/in/aaron-berg-26150917/&#34;&gt;Aaron Berg&lt;/a&gt; is a Customer Success Representative at RStudio.&lt;a href=&#34;#fnref1&#34;&gt;↩&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;To recreate this minimal example for yourself, please download the files from &lt;a href=&#34;https://gist.github.com/agberg/d71d3aacb9b9d5691b7ba7ab7555ba5b&#34;&gt;this gist&lt;/a&gt;.&lt;a href=&#34;#fnref2&#34;&gt;↩&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;The &lt;a href=&#34;https://github.com/wch/webshot&#34;&gt;&lt;code&gt;webshot&lt;/code&gt;&lt;/a&gt; package requires phantomJS to be installed as an external dependency, but will work on all systems. &lt;a href=&#34;https://github.com/hrbrmstr/decapitated&#34;&gt;&lt;code&gt;decapitated&lt;/code&gt;&lt;/a&gt; will only work on systems with versions of Chrome that can operate in &lt;a href=&#34;https://developers.google.com/web/updates/2017/04/headless-chrome&#34;&gt;headless mode&lt;/a&gt;.&lt;a href=&#34;#fnref3&#34;&gt;↩&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/06/28/printing-from-flex-dashboard/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Mapping Quandl Data with Shiny</title>
      <link>https://rviews.rstudio.com/2017/06/14/mapping-quandl-data-with-shiny/</link>
      <pubDate>Wed, 14 Jun 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/06/14/mapping-quandl-data-with-shiny/</guid>
      <description>
        
&lt;!-- BLOGDOWN-HEAD --&gt;
&lt;!-- /BLOGDOWN-HEAD --&gt;

&lt;!-- BLOGDOWN-BODY-BEFORE --&gt;
&lt;!-- /BLOGDOWN-BODY-BEFORE --&gt;
&lt;p&gt;Today, we are going to wrap our previously built &lt;a href=&#34;https://rviews.rstudio.com/2017/05/10/mapping-quandl-macroeconomic-data/&#34;&gt;Quandl/world map Notebook&lt;/a&gt; into an interactive Shiny app that lets users choose both a country and a data set for display. As usual, we did a lot of the heavy lifting in the Notebook to make our work more reproducible and our app more performant. The final app is available &lt;a href=&#34;http://colorado.rstudio.com:3939/worldmap-quandl-shiny/&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Devotees of this Reproducible Finance blog series will note similarities to this &lt;a href=&#34;http://colorado.rstudio.com:3939/Global-ETF-Map/&#34;&gt;Shiny app&lt;/a&gt;, but today’s app will have different and richer functionality.&lt;/p&gt;
&lt;p&gt;First, we are going to be pulling in data from Quandl, so we won’t be using ticker symbols, but rather will be using country codes plus data set codes. That would allow us to open this app to the vast number of data sets available via Quandl.&lt;/p&gt;
&lt;p&gt;Second, the user will be able to use the sidebar to select different data sets, rather than being restricted to a country ETF. For example, the user might want to select GDP-per-capita, or the exchange rate, or any data set that we wish to make available. Our app today will include 6 economic indicators.&lt;/p&gt;
&lt;p&gt;Third, we will display a chart using &lt;code&gt;highcharter&lt;/code&gt; instead of &lt;code&gt;dygraphs&lt;/code&gt;. There’s not a substantive reason to be doing this, beyond that it’s a good chance to start exploring &lt;code&gt;highcharter&lt;/code&gt;, which is a popular tool in the financial world.&lt;/p&gt;
&lt;p&gt;Lastly, we’ll port raw data to a &lt;code&gt;data.table&lt;/code&gt; and include a few buttons for easy download, in case our end users want to reproduce our charts or import data for their own work. We are going to use the &lt;code&gt;as_tibble&lt;/code&gt; function from the fantastically useful new &lt;a href=&#34;https://cran.r-project.org/web/packages/tidyquant/index.html&#34;&gt;tidyquant&lt;/a&gt; package to facilitate our &lt;code&gt;data.table&lt;/code&gt;. We won’t have space to cover the data download section in this post, but all the code is available in the live app.&lt;/p&gt;
&lt;p&gt;Without further ado, let’s get to it.&lt;/p&gt;
&lt;p&gt;The first line of substance in this app loads in the &lt;code&gt;leaflet&lt;/code&gt; map we constructed in our Notebook. We named the object &lt;code&gt;leaf_world&lt;/code&gt; and saved it in a file called &lt;code&gt;wdiMapData.RDat&lt;/code&gt;. If you want to refresh your memory on how we did that, have a look back at the &lt;a href=&#34;https://rviews.rstudio.com/2017/05/10/mapping-quandl-macroeconomic-data/&#34;&gt;previous post&lt;/a&gt;. Apologies if that sounds tedious, but hopefully it emphasizes the workflow of doing the heavy map-building in the Notebook when possible. If you or your team ever want to use that map as the basis for another Shiny app, that Notebook will be convenient to reuse.&lt;/p&gt;
&lt;p&gt;To load our map, we run the following:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Load the .RDat file where the leaflet map is saved.
load(&amp;#39;wdiMapData.RDat&amp;#39;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can access whatever R objects were saved in that file and, in this case, that means one R object called &lt;code&gt;leaf_world&lt;/code&gt;. That might not be a great name, but it’s the leaflet map of the world we built in the Notebook. When we are ready to build the map in our Shiny app, we’ll simply render that object.&lt;/p&gt;
&lt;p&gt;Before we get to the map, though, let’s construct a sidebar where the user can choose which data set to display. We are going to be working with a macroeconomic data source from the World Bank called World Development Indicators &lt;a href=&#34;http://data.worldbank.org/products/wdi&#34;&gt;WDI&lt;/a&gt;. The Quandl code for WDI is &lt;code&gt;WWDI&lt;/code&gt; and thus we’ll append &lt;code&gt;WWDI/&lt;/code&gt; to each data set call - but note that this will not appear in the sidebar because we won’t actually pass any data to Quandl there. We have to wait for the user to click on a county, and thus will handle the data passing in a future code chunk. This sidebar has one purpose: for the user to select the code for the economic indicator.&lt;/p&gt;
&lt;p&gt;We want to give the user a drop-down of choices, but we don’t want the choices to be the Quandl codes. We want the choices to be the familiar names of the data sets. In other words, the user will see as a choice ‘GDP Per Capita’, instead of the Quandl code &lt;code&gt;_NY_GDP_PCAP_KN&lt;/code&gt;. For that reason, we’ll first create an object called &lt;code&gt;dataChoices&lt;/code&gt; that holds our name-value pairs. The name is the familiar title of the time series - for example, ’GDP Per Capita` - and the value is the Quandl code.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dataChoices &amp;lt;- c(&amp;quot;GDP Per Capita&amp;quot; = &amp;quot;_NY_GDP_PCAP_KN&amp;quot;,
                  &amp;quot;GDP Per Capita Growth&amp;quot; = &amp;quot;_NY_GDP_PCAP_KD_ZG&amp;quot;,
                  &amp;quot;Real Interest Rate&amp;quot; = &amp;quot;_FR_INR_RINR&amp;quot;,
                  &amp;quot;Exchange Rate&amp;quot; = &amp;quot;_PX_REX_REER&amp;quot;,
                  &amp;quot;CPI&amp;quot; = &amp;quot;_FP_CPI_TOTL_ZG&amp;quot;,
                  &amp;quot;Labor Force Part. Rate&amp;quot; = &amp;quot;_SL_TLF_ACTI_ZS&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, in our &lt;code&gt;selectInput&lt;/code&gt; statement, we will set choices equal to &lt;code&gt;dataChoices&lt;/code&gt;, which will allow the user to see intuitive names but choose the Quandl codes.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;selectInput(&amp;quot;indicatorSelect&amp;quot;, 
            &amp;quot;Choose an economic indicator&amp;quot;,
            # Give the user a choice from the object we created above.
            choices = dataChoices,
            selected = &amp;quot;GDP Per Capita&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our simple sidebar is finished, and the end result is that when a user makes a choice, we have an input reactive with the value of the data set code. Let’s put that code aside for a minute and turn our attention to the map.&lt;/p&gt;
&lt;p&gt;Remember, we did the map-building work on this in our &lt;a href=&#34;https://rviews.rstudio.com/2017/05/10/mapping-quandl-macroeconomic-data/&#34;&gt;Notebook&lt;/a&gt;, then loaded the object in the &lt;code&gt;setup&lt;/code&gt; code chunk. That leaves us with a simple call to &lt;code&gt;renderLeaflet()&lt;/code&gt; to pass it &lt;code&gt;leaf_world&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;leafletOutput(&amp;quot;map1&amp;quot;)

output$map1 &amp;lt;- renderLeaflet({
  leaf_world
  })&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alright, that wasn’t too cumbersome, and perhaps the simplicity of that step makes the hard work in the previous Notebook a bit more tolerable.&lt;/p&gt;
&lt;p&gt;And now the fun part, wherein we build the machinery to let a user click the map and grab data from Quandl. We will proceed in four steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;capture the country code of the country that gets clicked&lt;/li&gt;
&lt;li&gt;call the economic time series that the user selected in the sidebar&lt;/li&gt;
&lt;li&gt;paste the country code and the time series together to create one data set code&lt;/li&gt;
&lt;li&gt;pass that one data set code to Quandl and import the time series&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On to step 1, capturing the clicked country.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;clickedCountry &amp;lt;- eventReactive(input$map1_shape_click, {
  return(input$map1_shape_click$id)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It’s same process we used in &lt;a href=&#34;https://rviews.rstudio.com/2016/12/16/reproducible-finance-with-r-a-shiny-etf-map/&#34;&gt;this post&lt;/a&gt;, but there is one difference. Let’s review what happened here.&lt;/p&gt;
&lt;p&gt;Recall that we set &lt;code&gt;layerID = ~iso_a3&lt;/code&gt; when we built the map in our Notebook. That’s because Quandl appends the iso_a3 country codes to the data set code. In other words, if we want GDP-per-capita for Brazil, we need the Brazil country code ‘BRA’ so we can later append it to the GDP-per-capita code ’_NY_GDP_PCAP_KN’.&lt;/p&gt;
&lt;p&gt;In the code chunk above, we used an &lt;code&gt;observeEvent&lt;/code&gt; function to capture the &lt;code&gt;layerID&lt;/code&gt; of whatever shape a user clicks, and in the Notebook, we had set that ID to be the &lt;code&gt;~isa_a3&lt;/code&gt; code. When a user clicks Brazil, our reactive captures the country code ‘BRA’.&lt;/p&gt;
&lt;p&gt;Next, we need to append that country code to the data set code. Recall that the user chose this code in our sidebar. We just need to grab his selection via another &lt;code&gt;reactive&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Nothing fancy here, a reactive value from our sidebar input.
indicatorValue &amp;lt;- reactive({input$indicatorSelect})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s pause and take inventory of what we have captured thus far: the country code from the click on the map is stored as &lt;code&gt;clickedCountry()&lt;/code&gt;, and the data set code from the sidebar is stored as &lt;code&gt;indicatorValue()&lt;/code&gt;. Now we want to paste those together and pass them to Quandl. We’ll do that via another &lt;code&gt;reactive&lt;/code&gt;, but we are also going to pass that pasted chain to Quandl in the reactive. Thus, the chunk below has one &lt;code&gt;reactive&lt;/code&gt; that does two things.&lt;/p&gt;
&lt;p&gt;First, it pastes together our inputs to form one data set code. Second, it passes that code to Quandl and returns the desired time series.&lt;/p&gt;
&lt;p&gt;Notice that when we paste the codes together, we start with &lt;code&gt;WWDI/&lt;/code&gt;. That’s because all of our data comes from the WWDI data source on Quandl. We are not letting the user choose a different data source. We could have done so in the sidebar, but consider how that would have complicated our data set code &lt;code&gt;reactive&lt;/code&gt; input in the sidebar.&lt;/p&gt;
&lt;p&gt;Back to our data import chunk wherein we create our data set code by pasting inputs together and then pass them to Quandl:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;countryData &amp;lt;- reactive({
  
  # WWDI is the World Bank data set. 
  # We aren&amp;#39;t giving the user a choice of data sources, but we could.
  dataSet &amp;lt;- paste(&amp;quot;WWDI/&amp;quot;,
                   # The country that was clicked.
                   as.character(clickedCountry()),
                   # The time series that was chosen in the sidebar.
                   as.character(indicatorValue()), 
                   sep = &amp;quot;&amp;quot;)
  # Now pass that pasted data set code object to Quandl.
  Quandl(dataSet, type = &amp;quot;xts&amp;quot;)
})  &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now have an object called &lt;code&gt;countryData&lt;/code&gt; that is an &lt;code&gt;xts&lt;/code&gt; object imported from Quandl. It holds the time series (1) from the WWDI data source, (2) for the country that was clicked, (3) for the economic indicator that was chosen in the sidebar&lt;/p&gt;
&lt;p&gt;From a data import perspective, we’re done. We could fit a model to this data, run forecasts, etc., but I am going to head straight to visualization using &lt;code&gt;highcharter&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;As mentioned at the outset, &lt;code&gt;dygraph&lt;/code&gt; would have done a fine job here, but &lt;code&gt;highcharter&lt;/code&gt; seems to be a more popular visualization tool in the financial industry, and that’s a good reason to start exploring its capabilities.&lt;/p&gt;
&lt;p&gt;The code chunk below might look heavy, but most of the lines are for aesthetics, creating a nice title and removing scroll bars that seem clunky to me. The key substantive statements below are &lt;code&gt;highchart(type = &amp;quot;stock&amp;quot;)&lt;/code&gt; and &lt;code&gt;hc_add_series(countryData())&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The first statement tells &lt;code&gt;highcharter&lt;/code&gt; to use its built-in stock format (this is good for graphing all sorts of economic time series, not just stocks), and the second passes our data object to the graphing function &lt;code&gt;hc_add_series&lt;/code&gt;. It’s a well-named function because it adds a series to the chart. If we wanted to include another series, we would use that same function and pass in another &lt;code&gt;xts&lt;/code&gt; object.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;output$highchart &amp;lt;- renderHighchart({
  
  # Make a nice title for the chart.
  # The next three linese are purely aesthetic to that our graph has an intuitive
  # title. 
  indicatorName1 &amp;lt;- names(dataChoices[dataChoices == input$indicatorSelect])
  countryName1 &amp;lt;- countrycode(as.character(clickedCountry()), &amp;quot;iso3c&amp;quot;, &amp;quot;country.name&amp;quot;)
  title &amp;lt;- paste(countryName1, indicatorName1, sep = &amp;quot; &amp;quot;)
  
  # Call highchart and ask nicely for it to use the built-in &amp;#39;stock&amp;#39; format.
  highchart(type = &amp;quot;stock&amp;quot;) %&amp;gt;% 
    hc_title(text = title) %&amp;gt;%
    # Pass our time series object countryData to highcharter function hc_add_series.
    hc_add_series(countryData(), name = title) %&amp;gt;%
    # I don&amp;#39;t like the look of the navigator/scrollbar in a small space, but others might. 
    # Change these to enabled = TRUE and check out the results.
    hc_navigator(enabled = FALSE) %&amp;gt;% 
    hc_scrollbar(enabled = FALSE)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That’s all for today. This post completes what we can retrospectively consider our 3-part series of Quandl Shiny apps. The other two posts are &lt;a href=&#34;https://rviews.rstudio.com/2017/04/21/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/&#34;&gt;here&lt;/a&gt; and &lt;a href=&#34;https://rviews.rstudio.com/2017/06/02/a-shiny-app-for-exploring-commodities-prices-and-economic-indicators-via-quandl/&#34;&gt;here&lt;/a&gt;. There are definitely interesting ways to combine the functionalities in these apps, but I’ll leave that to the awesome community of Shiny developers.&lt;/p&gt;
&lt;p&gt;See you next time, when we visit the wonderful world of portfolio theory and volatility!&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/06/14/mapping-quandl-data-with-shiny/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>A Shiny App for Exploring Commodities Prices and Economic Indicators, via Quandl</title>
      <link>https://rviews.rstudio.com/2017/06/02/a-shiny-app-for-exploring-commodities-prices-and-economic-indicators-via-quandl/</link>
      <pubDate>Fri, 02 Jun 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/06/02/a-shiny-app-for-exploring-commodities-prices-and-economic-indicators-via-quandl/</guid>
      <description>
        
&lt;!-- BLOGDOWN-HEAD --&gt;
&lt;!-- /BLOGDOWN-HEAD --&gt;

&lt;!-- BLOGDOWN-BODY-BEFORE --&gt;
&lt;!-- /BLOGDOWN-BODY-BEFORE --&gt;
&lt;p&gt;In a &lt;a href=&#34;https://rviews.rstudio.com/2017/04/12/copper-gold-and-ten-year-treasury-notes/&#34;&gt;previous post&lt;/a&gt;, we created an R Notebook to explore the relationship between the copper/gold price ratio and 10-year Treasury yields (if you’re curious why we might care about this relationship, have a quick look at that previous post), relying on data from Quandl. Today, we’ll create a Shiny app that lets users choose which different commodities ratios and different economic indicators to investigate. Perhaps users don’t care about Dr. Copper and Treasury yields, but instead want to explore the oil/gold price ratio and how it correlates with the US inflation rate, or the EU inflation rate. Let’s give them some flexibility!&lt;/p&gt;
&lt;p&gt;The finished app is available &lt;a href=&#34;http://colorado.rstudio.com:3939/commodities-ratio-quandl/&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Before we get to it, note a few issues that we have seen in the past.&lt;/p&gt;
&lt;p&gt;Very similar to our &lt;a href=&#34;https://rviews.rstudio.com/2017/04/21/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/&#34;&gt;previous Shiny app&lt;/a&gt;, in the code chunk below, we have some important decisions about how a user selects a commodity. We could use &lt;code&gt;textInput&lt;/code&gt; to allow the user to enter the code for the desired data set which would not limit the user in any way - he or she could choose any dataset on Quandl. The cost would be that the user would need to know, or go to Quandl and look up, the code for any data set.&lt;/p&gt;
&lt;p&gt;For example, to import iron ore prices, the user would have to type in ODA/PIORECR_USD. That’s a big problem if your end users are not familiar with and have no interest in data set codes. To emphasize convenience and usability we will go with &lt;code&gt;selectInput&lt;/code&gt; instead of &lt;code&gt;textInput&lt;/code&gt;, meaning our app will show a drop-down of a few choices. The user just clicks on “Iron Ore” instead of typing ODA/PIORECR_USD, or clicks on “copper” instead of typing CHRIS/CME_HG1.1. But, if a user wants to work with a data set that we haven’t included, said user is out of luck.&lt;/p&gt;
&lt;p&gt;Another big decision is how many choices to give the user. I’ve included a few: copper, oil, iron, platinum, palladium and silver. That’s a nice smattering of commodities whose prices tend to rise with a growing economy, plus silver which does not. I included silver so we could take a look at a commodity that should behave differently from the rest. As always, our choice here is driven by how broad this app should be. We could have added steel, lead, zinc, and tin, or we could have included just copper, oil and iron, depending on the use case. Either way, the number of drop downs is another tradeoff between usability and flexibility.&lt;/p&gt;
&lt;p&gt;The final decision is a bit more nuanced and requires looking ahead to how these inputs will be used further down in the app. Have a peak at the object called &lt;code&gt;commodityChoices&lt;/code&gt; and you might notice that we don’t strictly need that object. We could have put the vector of choices as an argment to selectInput, so that our code would have read &lt;code&gt;choices = c(&amp;quot;Copper&amp;quot; = &amp;quot;CHRIS/CME_HG1.1&amp;quot;, ...)&lt;/code&gt; instead of &lt;code&gt;choices = commodityChoices&lt;/code&gt;. In that choice assignment, “copper” is called the name and “CHRIS/CME_HG1.1” is called the value (together we can think of them as a name-value pair). The reason for building a separate &lt;code&gt;commodityChoices&lt;/code&gt; object is that we want the ability to extract either the name or the value of the name-value pair. Usually we would care only about the value, because we want to pass the value to Quandl and import the data, but that name is going to be useful when we label our graphs.&lt;/p&gt;
&lt;p&gt;Without further adieu, let’s look at &lt;code&gt;commodityChoices&lt;/code&gt;, &lt;code&gt;econIndicatorChoices&lt;/code&gt; and the use of &lt;code&gt;selectInput&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Create a vector of commodity choices. 
commodityChoices &amp;lt;- c(
                  &amp;quot;Copper&amp;quot; = &amp;quot;CHRIS/CME_HG1&amp;quot;,
                  &amp;quot;WTI oil&amp;quot; = &amp;quot;FRED/DCOILWTICO&amp;quot;,# 
                  &amp;quot;Iron Ore&amp;quot; = &amp;quot;ODA/PIORECR_USD&amp;quot;, # monthly
                  &amp;quot;Platinum&amp;quot; = &amp;quot;LPPM/PLAT&amp;quot;, 
                  &amp;quot;Palladium&amp;quot; = &amp;quot;LPPM/PALL&amp;quot;,
                  &amp;quot;Silver&amp;quot; = &amp;quot;LBMA/SILVER&amp;quot;) 

# Make those commodity choices avaible via selectInput.
selectInput(&amp;quot;commodity&amp;quot;,
            &amp;quot;Commodity&amp;quot;,
            choices = commodityChoices, 
            selected = &amp;quot;Copper&amp;quot;)

# Create a vector of economic indicator choices.
econIndicatorChoices &amp;lt;- c(
                  &amp;quot;10-Yr Yield&amp;quot; = &amp;quot;FRED/DGS10&amp;quot;, # daily
                  &amp;quot;US CPI&amp;quot; = &amp;quot;RATEINF/INFLATION_USA&amp;quot;,# monthly
                  &amp;quot;Japan CPI&amp;quot; = &amp;quot;RATEINF/INFLATION_JPN&amp;quot;,
                  &amp;quot;EU CPI&amp;quot; = &amp;quot;RATEINF/INFLATION_EUR&amp;quot;)

# Make those economic indicator choices avaible via selectInput.
selectInput(&amp;quot;econIndicator&amp;quot;,
            &amp;quot;Economic Indicator&amp;quot;,
            choices = econIndicatorChoices, 
            selected = &amp;quot;10-yr Yield&amp;quot;)
 
# A standard date range input.
dateRangeInput(&amp;quot;dateRange&amp;quot;,
               &amp;quot;Date range&amp;quot;,
               start = &amp;quot;1990-01-01&amp;quot;,
               end   = &amp;quot;2016-12-31&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now that we have the inputs in a sidebar for the user, it’s back to Quandl to import the data for the chosen commodity, gold and the chosen economic indicator. There’s a common date range for all three so we’ll start by creating start and end date objects.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ratio_indicator &amp;lt;- reactive({

Quandl.api_key(&amp;quot;your API key here&amp;quot;)

start_date &amp;lt;- format(input$dateRange[1])
end_date &amp;lt;- format(input$dateRange[2])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We could now write three separate calls to Quandl for each of the data sets but, instead, let’s make use of the &lt;code&gt;map()&lt;/code&gt; function from the &lt;code&gt;purrr&lt;/code&gt; package. If you’re not familiar with &lt;code&gt;purrr&lt;/code&gt;, have a look &lt;a href=&#34;https://cran.r-project.org/web/packages/purrr/purrr.pdf&#34;&gt;here&lt;/a&gt;. I’ll just say that you’ll probably never have to use &lt;code&gt;lapply()&lt;/code&gt; again (and that should be motivation enough), but, in short, the family of &lt;code&gt;map()&lt;/code&gt; functions takes a function and applies it to the elements in a vector, similar to the &lt;code&gt;apply()&lt;/code&gt; functions.&lt;/p&gt;
&lt;p&gt;Before we can use &lt;code&gt;map()&lt;/code&gt; though, we need a vector to feed it. Let’s create a vector of Quandl codes.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Create a vector of 3 data set codes
# 1) commodity chosen by user
# 2) gold quandl code
# 3) economic indicator chosen by user

gold_code &amp;lt;- &amp;quot;CHRIS/CME_GC1.1&amp;quot;
# Vector of Quandl codes.
data_set_codes &amp;lt;- c(input$commodity, gold_code, input$econIndicator)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we’ll apply the &lt;code&gt;Quandl()&lt;/code&gt; function by piping our vector of codes and using &lt;code&gt;map()&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Pipe the data_set_codes vector to Quandl via the map() function
# Note we can still set the start and end date and object type
# as we always can with Quandl.

 quandlData&amp;lt;- data_set_codes  %&amp;gt;% 
        # Pipe the datasets vector to Quandl via the map() function.
        map(Quandl,
            start_date = start_date,
            end_date = end_date,
            collapse = &amp;quot;monthly&amp;quot;,
            type = &amp;quot;xts&amp;quot;)     %&amp;gt;%&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we will use &lt;code&gt;map()&lt;/code&gt; to apply the &lt;code&gt;na.locf()&lt;/code&gt; function to our time series and ensure that no NAs remain.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;        # Replace all NAs using map() and na.locf().
        map(na.locf, formLast = TRUE) %&amp;gt;%&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we stopped here, we would have a list of three xts series, but I don’t want a list, I want one xts object. So, we’ll pipe our list of three and use the &lt;code&gt;reduce()&lt;/code&gt; + &lt;code&gt;merge()&lt;/code&gt; to combine our list of 3 time series into one xts object.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;        # Merge to one xts object using map() and merge().
        reduce(merge) %&amp;gt;% 
        # Add nicer column names.
        `colnames&amp;lt;-`(c(names(commodityChoices[commodityChoices == input$commodity]), 
                            &amp;quot;Gold&amp;quot;,
                            names(econIndicatorChoices[econIndicatorChoices == input$econIndicator]))) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alright, after running our Quandl codes through that series of mapped functions, we have three time series stored in one xts object, and now we want to calculate the price ratio of the chosen commodity/gold.&lt;/p&gt;
&lt;p&gt;To create that price ratio, we need to divide the first column by the second column and we’ll store it in a new column called &lt;code&gt;ratio&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Then we will save just that ratio and the economic indicator column data into their xts object. That is not necessary but it makes things cleaner and easier when we pass to &lt;code&gt;dygraph()&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Create a column and add the price ratio.
quandlData$ratio &amp;lt;- quandlData[,1]/quandlData[,2]

# Save just the ratio and the economic indicator data.
ratio_indicator  &amp;lt;- merge(quandlData$ratio, quandlData[,3])

# Add more general names.
colnames(ratio_indicator) &amp;lt;- c(&amp;quot;ratio&amp;quot;,&amp;quot;indicator&amp;quot;)       

return(ratio_indicator)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we just need to pass our reactive object &lt;code&gt;ratio_indicator()&lt;/code&gt; to &lt;code&gt;dygraph()&lt;/code&gt; and follow the same steps as we did when testing in our Notebook.&lt;/p&gt;
&lt;p&gt;We will use &lt;code&gt;dyRoller()&lt;/code&gt; to smooth out our chart and make each point an average of the number of periods specified with &lt;code&gt;rollPeriod = X&lt;/code&gt;. This won’t affect our xts object, where we store the data, it just makes the chart more readable.&lt;/p&gt;
&lt;p&gt;Remember also that we are charting two time series on the same chart and they are on different scales, so we want to add a right-hand-side y-axis.&lt;/p&gt;
&lt;p&gt;To do so, we need to invoke &lt;code&gt;dyAxis()&lt;/code&gt; for the left-hand axis, called “y”. Then we invoke &lt;code&gt;dyAxis()&lt;/code&gt; for the right-hand axis, called “y2”. We also need to set &lt;code&gt;independentTicks = TRUE&lt;/code&gt; so that we can use a unique, independent value scale for the right-hand side. Next, in our &lt;code&gt;dySeries()&lt;/code&gt; call for each time series, we assign each one to an axis. Here we assign “ratio” with &lt;code&gt;axis = &#39;y&#39;&lt;/code&gt;, so that the commodity-gold price ratio will be on the left-hand scale, and we assign “indicator” with &lt;code&gt;axis = &#39;y2&#39;&lt;/code&gt;, so the economic indicator will be on the right-hand scale.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dygraphOutput(&amp;quot;ratio_indicator&amp;quot;)

output$ratio_indicator &amp;lt;- renderDygraph({
  dygraph(ratio_indicator()) %&amp;gt;% 
    
  # Add the rollPeriod for smoothing.
  dyRoller(rollPeriod = 3) %&amp;gt;% 
    
  # Create two independent axes, just we did in the Notebook.
  dyAxis(&amp;quot;y&amp;quot;, label = &amp;quot;USD&amp;quot;) %&amp;gt;%
  dyAxis(&amp;quot;y2&amp;quot;, label = &amp;quot;Percent (%)&amp;quot;, independentTicks = TRUE) %&amp;gt;%
    
  # Assign each time series to an axis. 
  # Use the name from the name-value pair to create nice labels for each.  
  dySeries(&amp;quot;ratio&amp;quot;, axis = &amp;#39;y&amp;#39;, 
           label = paste(names(commodityChoices[commodityChoices == input$commodity]), 
                         &amp;quot;/Gold (LHS)&amp;quot;, sep = &amp;quot;&amp;quot;), color = &amp;quot;blue&amp;quot;) %&amp;gt;% 
  dySeries(&amp;quot;indicator&amp;quot;, axis = &amp;#39;y2&amp;#39;, 
           label = paste(names(econIndicatorChoices[econIndicatorChoices == input$econIndicator]), 
                         &amp;quot;(RHS)&amp;quot;, sep = &amp;quot;&amp;quot;), color = &amp;quot;red&amp;quot;)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We could end things here but let’s go ahead and add a chart to show the rolling correlation between the ratio and the indicator. We’ve done so much work to calculate and wrangle these time series, might as well put them to use!&lt;/p&gt;
&lt;p&gt;First, we’ll calculate the rolling correlation using the &lt;code&gt;rollapply()&lt;/code&gt; function. Nothing too complicated here.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dygraphOutput(&amp;quot;rollingCorrelation&amp;quot;)

output$rollingCorrelation &amp;lt;- renderDygraph({
  
rolling_cor &amp;lt;- rollapply(ratio_indicator(), 24,
                         function(x) cor(x[, 1], x[, 2], use = &amp;quot;pairwise.complete.obs&amp;quot;),
                         by.column = FALSE)
# Make a nicer name for the xts object that stores the rolling correlation. 
# This name will be displayed when a user hovers on the dygraph. 
names(rolling_cor) &amp;lt;- paste(names(commodityChoices[commodityChoices == input$commodity]),
                            &amp;quot;/Gold &amp;quot;,
                            names(econIndicatorChoices[econIndicatorChoices == input$econIndicator]), 
                            &amp;quot; Correlation&amp;quot;, sep = &amp;quot;&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It’s not necessary, but I like to display the mean, minimum and maximum rolling correlations on the chart. We’ll store those in three objects: &lt;code&gt;avg&lt;/code&gt;, &lt;code&gt;mini&lt;/code&gt;, and &lt;code&gt;maxi&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  avg  &amp;lt;- round(mean(rolling_cor, na.rm = T), 2)
  mini &amp;lt;- round(min(rolling_cor,  na.rm = T), 2)
  maxi &amp;lt;- round(max(rolling_cor,  na.rm = T), 2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we pass our &lt;code&gt;rolling_cor&lt;/code&gt; xts object to &lt;code&gt;dygraph()&lt;/code&gt; and pass the mean, minimum and maximum objects to &lt;code&gt;dyLimit()&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dygraph(rolling_cor, main = paste(names(commodityChoices[commodityChoices == input$commodity]),
                            &amp;quot;/Gold &amp;quot;,
                            names(econIndicatorChoices[econIndicatorChoices == input$econIndicator]), 
                            &amp;quot; Correlation&amp;quot;, sep = &amp;quot;&amp;quot;)) %&amp;gt;% 
  dyRangeSelector(dateWindow = c(&amp;quot;2015-01-01&amp;quot;, &amp;quot;2016-12-31&amp;quot;))  %&amp;gt;% 
  # Add a line for the mean, min and max.
  dyLimit(avg, color = &amp;#39;purple&amp;#39;) %&amp;gt;% 
  dyLimit(mini, color = &amp;#39;red&amp;#39;) %&amp;gt;% 
  dyLimit(maxi, color = &amp;#39;blue&amp;#39;) %&amp;gt;% 
  # Add an event for the US election.
  dyEvent(&amp;quot;2016-11-08&amp;quot;, &amp;quot;Trump!&amp;quot;, labelLoc = &amp;quot;bottom&amp;quot;)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And, we’re done! It’s fun to explore different relationships amongst different time series with this app. And once we have this template in the toolkit, all sorts of different data sets can be substituted in for exploration. For example, we might want to port this work over to a currencies dashboard, or a country GDP dashboard. The nice thing is, it’s just a matter of finding the right Quandl codes and imagining new hypotheses to explore.&lt;/p&gt;
&lt;p&gt;Things got a little choppy today with all the piping, so just a reminder that if you want the reusable code for this app, it’s available via the &lt;code&gt;source code&lt;/code&gt; button at the top right of the live app. Thanks, and see you next time.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/06/02/a-shiny-app-for-exploring-commodities-prices-and-economic-indicators-via-quandl/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Growth of DataFest over the years</title>
      <link>https://rviews.rstudio.com/2017/05/24/growth-of-datafest-over-the-years/</link>
      <pubDate>Wed, 24 May 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/05/24/growth-of-datafest-over-the-years/</guid>
      <description>
        
&lt;script src=&#34;/rmarkdown-libs/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/jquery/jquery.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;/rmarkdown-libs/leaflet/leaflet.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;/rmarkdown-libs/leaflet/leaflet.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;/rmarkdown-libs/leafletfix/leafletfix.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;link href=&#34;/rmarkdown-libs/leaflet-label/leaflet.label.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;/rmarkdown-libs/leaflet-label/leaflet.label.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/Proj4Leaflet/proj4-compressed.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/Proj4Leaflet/proj4leaflet.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/leaflet-binding/leaflet.js&#34;&gt;&lt;/script&gt;

&lt;p&gt;In &lt;a href=&#34;/2017/04/05/datafestorg/&#34;&gt;a previous post&lt;/a&gt;, I introduced DataFest and how one can streamline the organization of this event using Google Forms and tools from the tidyverse. In this post, I’ll walk through building a Shiny app that demonstrates the growth of DataFest over the years, both in terms of host locations and participating institutions, as well as in terms of the number of students who participated in each event.&lt;/p&gt;
&lt;p&gt;Here is a list of all packages used in this article:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(tidyverse)
library(googlesheets)
library(devtools)
library(ggmap)
library(stringr)
library(leaflet)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The data were contributed by the event organizers, and were collected using &lt;a href=&#34;https://goo.gl/forms/jlLC9B7aVIaF1QoQ2&#34;&gt;a Google Form&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To begin, the data are read using the &lt;code&gt;googlesheets&lt;/code&gt; package.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;datafest_wide &amp;lt;- gs_title(&amp;quot;DataFest over the years (Responses)&amp;quot;) %&amp;gt;%
  gs_read()&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;data-prep&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Data prep&lt;/h2&gt;
&lt;p&gt;Then minimal manipulation is applied to column names, and a new column concatenating city, state, and country is added to be used in geocoding.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# rename columns
yrs &amp;lt;- sort(rep(2011:2017, 3))
cols &amp;lt;- c(&amp;quot;df_&amp;quot;, &amp;quot;num_part_&amp;quot;, &amp;quot;other_inst_&amp;quot;)

names(datafest_wide) &amp;lt;- c(&amp;quot;timestamp&amp;quot;, &amp;quot;host&amp;quot;, &amp;quot;city&amp;quot;, &amp;quot;state&amp;quot;, &amp;quot;country&amp;quot;, &amp;quot;url&amp;quot;,
                     paste0(cols, yrs))

# geocode host location
datafest_wide &amp;lt;- datafest_wide %&amp;gt;%
  mutate(address = paste(city, state, country)) %&amp;gt;% 
  mutate_geocode(address)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that we need to use the development version of the &lt;code&gt;ggmap&lt;/code&gt; package for &lt;code&gt;mutate_geocode()&lt;/code&gt; to play nicely with a &lt;code&gt;tbl_df&lt;/code&gt;. You can install this version with &lt;code&gt;install_github(&amp;quot;dkahle/ggmap&amp;quot;)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Next, we convert the data from wide to long format using functionality from the &lt;code&gt;tidyr&lt;/code&gt; package. First, we gather the columns that contain yearly information (for each year, we have an indicator for whether an event was hosted at the location, the number of students that participated, and other participating institutions, if any). Then, we strip the year information from variable names, and instead save it as a variable in the dataset. Finally, we spread the key-value pair across three columns.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;datafest_long &amp;lt;- datafest_wide %&amp;gt;% 
  gather(key, value, df_2011:other_inst_2017) %&amp;gt;%
  mutate(year = as.numeric(str_match(key, &amp;quot;[0-9]+&amp;quot;))) %&amp;gt;%
  mutate(key = str_replace(key, &amp;quot;_[0-9]+&amp;quot;, &amp;quot;&amp;quot;)) %&amp;gt;%
  spread(key, value) %&amp;gt;%
  mutate(num_part = as.numeric(num_part))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;map-of-2017-asa-datafests&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Map of 2017 ASA DataFests&lt;/h2&gt;
&lt;p&gt;The eventual goal of this post is to make a Shiny app that maps DataFest spread and growth over the years; however, I’ll start by making a map for just one year, 2017, to develop the code for the map, and then use this code within a Shiny app.&lt;/p&gt;
&lt;p&gt;Going forward, I’ll refer to the long dataset as &lt;code&gt;datafest&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;datafest &amp;lt;- datafest_long&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;First, I take a subset of the data for hosts that held an event in 2017:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;datafest_2017 &amp;lt;- filter(datafest, year == 2017 &amp;amp; df == &amp;quot;Yes&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then, I set a few colors to be used in the plot,&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;href_color &amp;lt;- &amp;quot;#A7C6C6&amp;quot;
marker_color &amp;lt;- &amp;quot;black&amp;quot;
part_color &amp;lt;- &amp;quot;#89548A&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;as well as the bounds of the plot based on the min/max longitude/latitude.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;left &amp;lt;- floor(min(datafest$lon))
right &amp;lt;- ceiling(max(datafest$lon))
bottom &amp;lt;- floor(min(datafest$lat))
top &amp;lt;- ceiling(max(datafest$lat))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I will be making the map using the &lt;code&gt;leaflet&lt;/code&gt; package, as this package allows for easily overlaying markers and popups to maps. The popups are text bubbles that appear when a point is clicked, and that contain additional information about that data point. This is a good place to add some event-specific information, such as name of host, and link to their event homepage, other participating institutions (if any), and number of participants.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;host_text &amp;lt;- paste0(
  &amp;quot;&amp;lt;b&amp;gt;&amp;lt;a href=&amp;#39;&amp;quot;, datafest_2017$url, &amp;quot;&amp;#39; style=&amp;#39;color:&amp;quot;, 
  href_color, &amp;quot;&amp;#39;&amp;gt;&amp;quot;, datafest_2017$host, &amp;quot;&amp;lt;/a&amp;gt;&amp;lt;/b&amp;gt;&amp;quot;
)

other_inst_text &amp;lt;- paste0(
  ifelse(is.na(datafest_2017$other_inst), 
         &amp;quot;&amp;quot;, 
         paste0(&amp;quot;&amp;lt;br&amp;gt;&amp;quot;, &amp;quot;with participation from &amp;quot;, datafest_2017$other_inst))
)

part_text &amp;lt;- paste0(
  &amp;quot;&amp;lt;font color=&amp;quot;, part_color,&amp;quot;&amp;gt;&amp;quot;, datafest_2017$num_part, 
  &amp;quot; participants&amp;lt;/font&amp;gt;&amp;quot;
)

popups &amp;lt;- paste0(
  host_text, other_inst_text, &amp;quot;&amp;lt;br&amp;gt;&amp;quot;, part_text
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We’re finally ready to make our map! Note that the radii of the points are proportional to the log of the number of participants (times an arbitrary factor for visual appeal).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;leaflet() %&amp;gt;%
  addTiles() %&amp;gt;%
  fitBounds(lng1 = left, lat1 = bottom, lng2 = right, lat2 = top) %&amp;gt;%
  addCircleMarkers(lng = datafest_2017$lon, lat = datafest_2017$lat,
                   radius = log(datafest_2017$num_part) * 1.2, 
                   fillColor = marker_color,
                   color = marker_color,
                   weight = 1,
                   fillOpacity = 0.5,
                   popup = popups)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;htmlwidget-1&#34; style=&#34;width:672px;height:480px;&#34; class=&#34;leaflet html-widget&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;options&#34;:{&#34;crs&#34;:{&#34;crsClass&#34;:&#34;L.CRS.EPSG3857&#34;,&#34;code&#34;:null,&#34;proj4def&#34;:null,&#34;projectedBounds&#34;:null,&#34;options&#34;:{}}},&#34;calls&#34;:[{&#34;method&#34;:&#34;addTiles&#34;,&#34;args&#34;:[&#34;//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&#34;,null,null,{&#34;minZoom&#34;:0,&#34;maxZoom&#34;:18,&#34;maxNativeZoom&#34;:null,&#34;tileSize&#34;:256,&#34;subdomains&#34;:&#34;abc&#34;,&#34;errorTileUrl&#34;:&#34;&#34;,&#34;tms&#34;:false,&#34;continuousWorld&#34;:false,&#34;noWrap&#34;:false,&#34;zoomOffset&#34;:0,&#34;zoomReverse&#34;:false,&#34;opacity&#34;:1,&#34;zIndex&#34;:null,&#34;unloadInvisibleTiles&#34;:null,&#34;updateWhenIdle&#34;:null,&#34;detectRetina&#34;:false,&#34;reuseTiles&#34;:false,&#34;attribution&#34;:&#34;&amp;copy; &lt;a href=\&#34;http://openstreetmap.org\&#34;&gt;OpenStreetMap&lt;\/a&gt; contributors, &lt;a href=\&#34;http://creativecommons.org/licenses/by-sa/2.0/\&#34;&gt;CC-BY-SA&lt;\/a&gt;&#34;}]},{&#34;method&#34;:&#34;addCircleMarkers&#34;,&#34;args&#34;:[[35.9940329,41.6959269,40.4167022,33.7489954,35.4993031,44.0153371,41.5623209,42.9721934,40.7933949,34.0522342,38.9517053,41.49932,39.9611755,33.7879139,37.8715926,39.5069974,42.3732216,35.0853336,40.7127837,49.4874592,37.2295733,38.9071923,41.49932,44.9537029,41.8781136,41.8239891,43.653226],[-78.898619,-73.8968025,-86.8752869,-84.3879824,-80.8486846,-73.16734,-72.6506488,-85.9540407,-77.8600012,-118.2436849,-92.3340724,-81.6943605,-82.9987942,-117.8531007,-122.272747,-84.745231,-72.5198537,-106.6055534,-74.0059413,8.4660395,-80.4139393,-77.0368707,-81.6943605,-93.0899578,-87.6297982,-71.4128343,-79.3831843],[7.06332483774019,5.18098573624357,5.25843196160866,4.56799498772438,4.64544121308947,3.86265098984184,5.18098573624357,3.70925094402998,5.52620422318571,6.84453896958744,3.59487872826479,3.86265098984184,5.6514362415748,5.00926472387476,4.69442760651378,5.39977160439632,5.94699246912151,3.16686879553831,4.56799498772438,5.25843196160866,4.91321347466652,4.8725316126557,3.32710646668774,4.78678085587713,4.42665534493672,4.42665534493672,4.42665534493672],null,null,{&#34;lineCap&#34;:null,&#34;lineJoin&#34;:null,&#34;clickable&#34;:true,&#34;pointerEvents&#34;:null,&#34;className&#34;:&#34;&#34;,&#34;stroke&#34;:true,&#34;color&#34;:&#34;black&#34;,&#34;weight&#34;:1,&#34;opacity&#34;:0.5,&#34;fill&#34;:true,&#34;fillColor&#34;:&#34;black&#34;,&#34;fillOpacity&#34;:0.5,&#34;dashArray&#34;:null},null,null,[&#34;&lt;b&gt;&lt;a href=&#39;http://stat.duke.edu/datafest&#39; style=&#39;color:#A7C6C6&#39;&gt;Duke University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from UNC Chapel Hill, NC State, North Carolina A&amp;T, Elon University, NCSSM, Meredith College, Wake Forest University&lt;br&gt;&lt;font color=#89548A&gt;360 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://pages.vassar.edu/datafest/&#39; style=&#39;color:#A7C6C6&#39;&gt;Vassar College&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from Marist College, Colgate University&lt;br&gt;&lt;font color=#89548A&gt;75 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://llc.stat.purdue.edu/datafest2016.html&#39; style=&#39;color:#A7C6C6&#39;&gt;Purdue University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;80 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://www.quantitative.emory.edu/events/datafest%20.html&#39; style=&#39;color:#A7C6C6&#39;&gt;Emory University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;45 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;https://www.davidson.edu/academics/mathematics-and-computer-science/student-activities/competitions/datafest&#39; style=&#39;color:#A7C6C6&#39;&gt;Davidson College&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;48 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://go.middlebury.edu/datafest&#39; style=&#39;color:#A7C6C6&#39;&gt;Middlebury College&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;25 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://datafest.blogs.wesleyan.edu/&#39; style=&#39;color:#A7C6C6&#39;&gt;Wesleyan University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from University of Connecticut, Connecticut College, Trinity College, Yale University, Lafayette College&lt;br&gt;&lt;font color=#89548A&gt;75 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://www.gvsu.edu/stat/datafest-50.htm&#39; style=&#39;color:#A7C6C6&#39;&gt;Grand Valley State University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;22 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://stat.psu.edu/Events/2016-datafest&#39; style=&#39;color:#A7C6C6&#39;&gt;Penn State University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from PSU Brandywine, PSU Harrisburg, PSU Great Valley, Wilkes University&lt;br&gt;&lt;font color=#89548A&gt;100 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://datafest.stat.ucla.edu/&#39; style=&#39;color:#A7C6C6&#39;&gt;UCLA&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from Pomona, Biola, Cal Poly SLO, UCR&lt;br&gt;&lt;font color=#89548A&gt;300 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;NA&#39; style=&#39;color:#A7C6C6&#39;&gt;University of Missouri&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;20 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;https://sites.google.com/view/csudatafest/home&#39; style=&#39;color:#A7C6C6&#39;&gt;Cleveland State University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;25 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;https://data-analytics.osu.edu/datafest&#39; style=&#39;color:#A7C6C6&#39;&gt;Ohio State University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;111 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://www.chapman.edu/scst/conferences-and-events/datafest.aspx&#39; style=&#39;color:#A7C6C6&#39;&gt;Chapman University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from UCSB, CSUN, USC, CSUF, UCI&lt;br&gt;&lt;font color=#89548A&gt;65 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;datafest.stat.berkeley.edu&#39; style=&#39;color:#A7C6C6&#39;&gt;UC Berkeley&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;50 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://miamioh.edu/fsb/centers/cads/experiential/datafest/&#39; style=&#39;color:#A7C6C6&#39;&gt;Miami University (Ohio)&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from University of Cincinnati; Bowling Green State University&lt;br&gt;&lt;font color=#89548A&gt;90 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://www.science.smith.edu/datafest/&#39; style=&#39;color:#A7C6C6&#39;&gt;University of Massachusets&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from Amherst, Hampshire, Mt. Holyoke, Smith Colleges&lt;br&gt;&lt;font color=#89548A&gt;142 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://math.unm.edu/news-events/events/asa-datafest&#39; style=&#39;color:#A7C6C6&#39;&gt;University of New Mexico&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;14 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://blogs.cuit.columbia.edu/statisticsclub/events/spring-datafest-2017/&#39; style=&#39;color:#A7C6C6&#39;&gt;Columbia University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;45 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://datafest.de/&#39; style=&#39;color:#A7C6C6&#39;&gt;University of Mannheim&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;80 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://www.stat.vt.edu/Academics/undergraduate/VTdatafest.html&#39; style=&#39;color:#A7C6C6&#39;&gt;Virginia Tech&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;60 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;https://www.facebook.com/events/520875878090896/&#39; style=&#39;color:#A7C6C6&#39;&gt;Summit Consulting, DC&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;with participation from George Washington, UMD, UMBC, American, Howard, George Washington&lt;br&gt;&lt;font color=#89548A&gt;58 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://mathstats.case.edu/datafest-2017/&#39; style=&#39;color:#A7C6C6&#39;&gt;Case Western Reserve University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;16 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;https://www.macalester.edu/datafest/&#39; style=&#39;color:#A7C6C6&#39;&gt;Macalaster College&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;54 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;http://pascal.math.luc.edu/datafest/&#39; style=&#39;color:#A7C6C6&#39;&gt;Loyola University Chicago&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;40 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;NA&#39; style=&#39;color:#A7C6C6&#39;&gt;Brown University&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;40 participants&lt;\/font&gt;&#34;,&#34;&lt;b&gt;&lt;a href=&#39;https://utorontodatafest.wordpress.com/&#39; style=&#39;color:#A7C6C6&#39;&gt;University of Toronto&lt;\/a&gt;&lt;\/b&gt;&lt;br&gt;&lt;font color=#89548A&gt;40 participants&lt;\/font&gt;&#34;],null,null,null,null]}],&#34;fitBounds&#34;:[33,-123,50,9],&#34;limits&#34;:{&#34;lat&#34;:[33.7489954,49.4874592],&#34;lng&#34;:[-122.272747,8.4660395]}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;/div&gt;
&lt;div id=&#34;shiny-app&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Shiny app&lt;/h2&gt;
&lt;p&gt;Next, we build upon our earlier plot to create a Shiny app that has the following three components:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;A slider input with animation for values between 2011 and 2017 (DataFest years, so far)&lt;/li&gt;
&lt;li&gt;A line plot that shows the increase in the number participants over the year&lt;/li&gt;
&lt;li&gt;A map that shows the spread of DataFest geographically over the years&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;You can find and interact with the app at &lt;a href=&#34;https://gallery.shinyapps.io/datafest-map-all-years/&#34; class=&#34;uri&#34;&gt;https://gallery.shinyapps.io/datafest-map-all-years/&lt;/a&gt;, and the code for the app, as well as all steps up to this point, can be found at &lt;a href=&#34;https://github.com/mine-cetinkaya-rundel/datafest-growth&#34;&gt;this GitHub repo&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;https://gallery.shinyapps.io/datafest-map-all-years/&#34;&gt; &lt;img src=&#34;/post/2017-05-22-growth-of-datafest-over-the-years_files/app.png&#34; alt=&#34;Screenshot of app&#34;&#34;&gt; &lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/05/24/growth-of-datafest-over-the-years/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Shiny in Medicine</title>
      <link>https://rviews.rstudio.com/2017/05/03/shiny-in-medicine/</link>
      <pubDate>Wed, 03 May 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/05/03/shiny-in-medicine/</guid>
      <description>
        

&lt;p&gt;Shiny Apps are becoming ubiquitous as a way for data scientists to present the results of an analysis, and also to engage with information consumers who may not be coders. The trend I see is that the greater the variety of skills and interests of the information consumers for any particular project, the more valued are interactive visualizations that can be integrated into enterprise-wide communication workflows. So, it is not surprising to see Shiny apps popping up in all manner of healthcare and medical applications. If data scientists are going to bring predictive analytics into clinical workflows where doctors, nurses, scientists, technicians and administrators are all part of near real-time decision processes, they are going to have to be even more inventive in providing these multi-skilled teams with low-friction tools to ingest and manipulate information. Below are few interesting Shiny apps that are broadly related to Health Care and Medicine. My guess is that interactive visualizations like these will improve research and clinical workflows, and eventually change how all of us look at Health Care and Medicine.&lt;/p&gt;
&lt;p&gt;The &lt;a href=&#34;https://gallery.shinyapps.io/genome_browser/&#34;&gt;Genome viewer&lt;/a&gt; for ICGC cancer, built by the folks at &lt;a href=&#34;http://www.aridhia.com/&#34;&gt;Aridhia&lt;/a&gt;, is geared towards researchers. You can learn how to interpret the plot and learn the story behind its creation &lt;a href=&#34;http://www.aridhia.com/blog/beauty-in-simplicity-visualising-large-scale-genomic-data/&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-26-shiny-in-medicine_files/app1.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;The &lt;a href=&#34;https://gallery.shinyapps.io/EDsimulation/&#34;&gt;Emergency Department Simulation&lt;/a&gt;, built by a group of mathematicians and physicians, models patient flow information under different assumptions about emergency department case loads, and illustrates how predictive analytics and statistical analysis can be integrated into operational clinical workflows.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-26-shiny-in-medicine_files/app2.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;The &lt;a href=&#34;http://riskcalc.org/ColorectalCancer/&#34;&gt;Colorectal Cancer risk calculator&lt;/a&gt; from the Cleveland Clinic targets physicians and the general public to personalize the risk of this disease. I found working through different “what if” scenarios of great help in thinking about the risk factors that are under my control.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-26-shiny-in-medicine_files/app3.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;Finally, these two Shiny Apps that provide information about US hospitals should be of interest to public health planners, as well as to the general public. The &lt;a href=&#34;http://datascience-enthusiast.com/R/Hospital_Rankings.html&#34;&gt;Hospital Ranking App&lt;/a&gt; compares hospital outcomes for heart attack, heart failure, and pneumonia against national statistics.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-26-shiny-in-medicine_files/app4.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;The &lt;a href=&#34;http://colorado.rstudio.com:3939/content/188/&#34;&gt;Access to Hospital Care Dashboard&lt;/a&gt; plots the density of hospitals throughout the United States, and indicates under-served areas.&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-26-shiny-in-medicine_files/app5.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;If you or your team are doing this kind of work, we here at R Views would love to hear about it.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/05/03/shiny-in-medicine/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>A Shiny App for Importing and Forecasting Commodities Prices from Quandl</title>
      <link>https://rviews.rstudio.com/2017/04/21/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/</link>
      <pubDate>Fri, 21 Apr 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/04/21/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/</guid>
      <description>
        
&lt;!-- BLOGDOWN-HEAD --&gt;
&lt;!-- /BLOGDOWN-HEAD --&gt;

&lt;!-- BLOGDOWN-BODY-BEFORE --&gt;
&lt;!-- /BLOGDOWN-BODY-BEFORE --&gt;
&lt;p&gt;In a &lt;a href=&#34;https://rviews.rstudio.com/2017/03/17/quandl-and-forecasting/&#34;&gt;previous post&lt;/a&gt;, we imported oil data from Quandl and applied a simple model to it. Today, we’ll port that work over to a Shiny app (by way of flexdashboard, of course) that allows a user to choose a commodity (oil, copper or gold), choose a frequency for the time series, and choose how many periods ahead to forecast. The app will display the price history and the forecasted price. To see it in action, have a look &lt;a href=&#34;http://colorado.rstudio.com:3939/commodities-quandl-flexdb/&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;As with the previous Notebook, the main purpose of this post is to build a template where a more sophisticated or proprietary model could be used for forecasting. By setting it up so that models could be selected as inputs, several different models could be included. We are not as concerned with the modeling as much as we are with providing a format that is friendly to both end users and any future collaborator that might want to take this app and expand upon it.&lt;/p&gt;
&lt;p&gt;Let’s get to it! In the code chunk below, we are immediately faced with a few important decisions. The first of those is the format of the user input. At the extreme, we could use &lt;code&gt;textInput&lt;/code&gt; and simply allow the user to enter the code for the desired data set. The benefit is that we would not limit the user in any way; he or she could choose any dataset on Quandl. The cost would be that the user would need to know - or go to Quandl and look up - the code for any data set.&lt;/p&gt;
&lt;p&gt;For example, to import WTI oil prices, the user would have to type in “FRED/DCOILWTICO”. That’s no problem if most of the end users know that code, but it’s a big problem otherwise. We want to emphasize convenience and broad usability, so we are going with &lt;code&gt;selectInput&lt;/code&gt; instead of &lt;code&gt;textInput&lt;/code&gt;, meaning our app will show a drop-down of a few choices. The user just selects “WTI oil” instead of typing “FRED/DCOILWTICO”“, or selects”copper&amp;quot; instead of typing “ODA/PCOPP_USD”. But, if a user wants to work with a data set that we haven’t included, said user is out of luck.&lt;/p&gt;
&lt;p&gt;Another big decision is how many choices to give the user. I have included only 3: oil, gold and copper. In industry, you would probably include several more, perhaps all of the industrial metals, but there’s is a cutoff somewhere. Or maybe we prefer one choice, because this app is just for oil analysis. Either way, the number of options in the drop-down menu is another trade-off between usability and flexibility.&lt;/p&gt;
&lt;p&gt;The final decision is a bit more nuanced, and requires looking ahead to how these inputs will be used further down in the app. Have a peek at the object called &lt;code&gt;dataChoices&lt;/code&gt;, and you might notice that we don’t strictly need that object. We could have put the vector of choices as an argument to &lt;code&gt;selectInput&lt;/code&gt;, so that our code would have read &lt;code&gt;choices = c(&amp;quot;WTI oil&amp;quot; = &amp;quot;FRED/DCOILWTICO&amp;quot;, ...)&lt;/code&gt; instead of &lt;code&gt;choices = dataChoices&lt;/code&gt;. In that choice assignment, “WTI oil” is called the name and “FRED/DCOILWTICO” is called the value (together we can think of them as a name-value pair). The entire reason for building a separate &lt;code&gt;dataChoices&lt;/code&gt; object is that we want the ability to extract either the name or the value of the name-value pair. Usually we would care only about the value, because we want to pass the value to Quandl and import the data, but that name is going to be useful as well when we label our graph.&lt;/p&gt;
&lt;p&gt;The ability to extract names and values will become even more useful when we get to the frequency of the time series and forecasting. For now, let’s look at &lt;code&gt;dataChoices&lt;/code&gt; and &lt;code&gt;selectInput&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Notice a tradeoff here: we&amp;#39;re making it easy on our users because they don&amp;#39;t need to 
# remember the naming conventions. But, we&amp;#39;re also forced to severely limit their choices. 
# The dataChoices object is going to allow us to add a nicer label to the graph. 
# Notice also how easily we can include datasets from different sources, and not worry about
# their formats. Thanks, Quandl!

dataChoices &amp;lt;- c(&amp;quot;WTI oil&amp;quot; = &amp;quot;FRED/DCOILWTICO&amp;quot;, # oil data from Fred
                 &amp;quot;Copper&amp;quot; = &amp;quot;ODA/PCOPP_USD&amp;quot;, # copper data from ODA
                 &amp;quot;Gold&amp;quot; = &amp;quot;CHRIS/CME_GC1&amp;quot;) # gold data from CME

selectInput(&amp;quot;dataSet&amp;quot;,
            &amp;quot;Commodity&amp;quot;,
            choices = dataChoices,
            selected = &amp;quot;WTI oil&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alright, we have given the user the ability to choose a commodity. Next we want to ask about the frequency, and this gets a bit more complicated. We need to tell Quandl the frequency of the time series to import using the “daily”, “weekly”, “monthly” convention, so we set those to the values. But, further down the app when we want to store the forecast results, we’ll need to use the “days”, “weeks”, “months” phrasing and we’ll need to pull out the names from the name-value pair in &lt;code&gt;frequencyChoices&lt;/code&gt;. We knew that this would be necessary because when we built our Notebook for importing, wrangling, and testing, we noted the different conventions and started thinking about how to deal with them in the Shiny context.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# The frequencyChoices object is going to allow us to pass different period conventions
# to different places further down the app. 

frequencyChoices &amp;lt;- c(&amp;quot;days&amp;quot; = &amp;quot;daily&amp;quot;,
                      &amp;quot;weeks&amp;quot; = &amp;quot;weekly&amp;quot;, 
                      &amp;quot;months&amp;quot; = &amp;quot;monthly&amp;quot;)

selectInput(&amp;quot;frequency&amp;quot;,
            &amp;quot;freq&amp;quot;,
            choices = frequencyChoices, 
            selected = &amp;quot;months&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The remainder of the inputs should look familiar as they are in standard format.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dateRangeInput(&amp;quot;dateRange&amp;quot;,
               &amp;quot;Date range&amp;quot;,
               start = &amp;quot;1980-01-01&amp;quot;,
               end   = &amp;quot;2016-12-31&amp;quot;)

numericInput(&amp;quot;periods&amp;quot;, &amp;quot;Periods to Forecast&amp;quot;, 6, min = 1, max = 100)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now that we’ve built the sidebar inputs, let’s put them to use. First, we will import the commodity time series data from Quandl. This will be familiar from the Notebook, but note in particular that we will use the value from the &lt;code&gt;input$frequency&lt;/code&gt; choice because Quandl uses the “daily/weekly/monthly” frequency format.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Let&amp;#39;s pull in the Quandl data. 
# Nothing fancy here except we are going to use the reactive inputs.
# We will pass in the value from the input$dataSet key-value pair.
# We will also pass in the value from the input$frequency key-value pair. 

commodity &amp;lt;- reactive({
  # It might be a good idea to include your quandl api key if this will be used more than 50 times in a day. 
  Quandl.api_key(&amp;quot;your_apikey_here&amp;quot;)
  
  commodity &amp;lt;- Quandl(input$dataSet,
                      start_date = format(input$dateRange[1]),
                      end_date = format(input$dateRange[2]),
                      order = &amp;quot;asc&amp;quot;,
                      type = &amp;quot;xts&amp;quot;,
                      collapse = as.character(input$frequency)
  )
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We have imported a time series object for the dataset, date range and frequency chosen by the user. Now we want to do some forecasting and create a visualization. We’ll first use the &lt;code&gt;forecast()&lt;/code&gt; function, then we’ll combine the forecasted prices and the historical prices into one xts object that can be passed to dygraph. Let’s handle this in one reactive.&lt;/p&gt;
&lt;p&gt;First, we’ll call &lt;code&gt;forecast&lt;/code&gt; and pass it the &lt;code&gt;periods&lt;/code&gt; input from the user.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;combined_xts &amp;lt;- reactive({
  
  # Just like the Notebook, except periods is a reactive input.
  
  forecasted &amp;lt;- forecast(commodity(), h = input$periods)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we need to combine that forecasted object with the commodity object that was created in a previous code chunk. Here we will finally thank ourselves for thinking about the name-value issue when assigning &lt;code&gt;frequencyChoices&lt;/code&gt;. When we create a dataframe to hold the forecasted time series, we build a ‘date’ column using the &lt;code&gt;seq()&lt;/code&gt; function. The column starts on the end date of the historical data (which the user selected with the &lt;code&gt;dateRange&lt;/code&gt; input) and runs for as many periods as the user chose in the &lt;code&gt;periods&lt;/code&gt; input. But, we need to supply a value to the &lt;code&gt;by = ...&lt;/code&gt; argument of the &lt;code&gt;seq()&lt;/code&gt; function so that it knows if we want to move 6 days, 6 weeks, 6 months, etc. To do that, we need to extract the name (“days/weeks/months”) from the &lt;code&gt;frequencyChoices&lt;/code&gt; name-value pair and pass it to seq. The way we extract the name is with this selection statement: &lt;code&gt;names(frequencyChoices[frequencyChoices == input$frequency])&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  forecast_dataframe &amp;lt;- data.frame(
    date = seq(input$dateRange[2], 
               # The next line is very important, and it&amp;#39;s the reason we 
               # created the frequencyChoices object.
               by = names(frequencyChoices[frequencyChoices == input$frequency]),
               length.out = input$periods),
    Forecast = forecasted$mean,
    Hi_95 = forecasted$upper[,2],
    Lo_95 = forecasted$lower[,2])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we convert the &lt;code&gt;forecast_dataframe&lt;/code&gt; object to an xts and combine that new object with the &lt;code&gt;commodity&lt;/code&gt; xts object. Remember, we imported the commodity data from Quandl in the form of an xts object, which saved us from having to do a conversion. This chunk should look very similar to the Notebook.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  forecast_xts &amp;lt;- xts(forecast_dataframe[,-1], order.by = forecast_dataframe[,1])
  
  combined_xts &amp;lt;- cbind(commodity(), forecast_xts)
  
  # Add a nicer name for the first column.
  
  colnames(combined_xts)[1] &amp;lt;- &amp;quot;Actual&amp;quot;
  
  # This is the combined object that will be passed to dygraphs below. 
  combined_xts
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we will create a chart of the actual price history. Nothing fancy here, except again we are going extract the ‘name’ portion of a name-value pair, this time from the &lt;code&gt;dataSet&lt;/code&gt; object (the first one we created in the first code chunk). We want to label the graph with ‘WTI oil’ and not the Quandl code, so we select the name with &lt;code&gt;names(dataChoices[dataChoices==input$dataSet])&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dygraphOutput(&amp;quot;commodity&amp;quot;)

output$commodity &amp;lt;- renderDygraph({
  dygraph(commodity(),
          # We pull out the name of the selected name-value input$dataSet like so: 
          # names(dataChoices[dataChoices==input$dataSet])
          main = paste(&amp;quot;Price history of&amp;quot;, names(dataChoices[dataChoices==input$dataSet]), 
                       sep = &amp;quot; &amp;quot;)) %&amp;gt;%
    dyAxis(&amp;quot;y&amp;quot;, label = &amp;quot;$&amp;quot;) %&amp;gt;%
    dyOptions(axisLineWidth = 1.5, fillGraph = TRUE, drawGrid = TRUE)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Last but not least, let’s graph the historical and forecasted time series together on one graph. We could have ported the code directly from the Notebook, but I couldn’t help tinkering just a bit. I wanted to focus the graph on the time period around where the actual data ends and the forecast begins, because that is probably what’s of most interest to the user. To do that, we’ll use the &lt;code&gt;dyRangeSelector()&lt;/code&gt; function and pass two values to the &lt;code&gt;dateWindow&lt;/code&gt; variable: a start date and end an date. This is pure aesthetics, but I think it’s worth the effort here.&lt;/p&gt;
&lt;p&gt;We are going to use &lt;code&gt;seq()&lt;/code&gt; and &lt;code&gt;names(frequencyChoices[frequencyChoices == input$frequency])&lt;/code&gt; once again.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dygraphOutput(&amp;quot;forecasted&amp;quot;)

output$forecasted &amp;lt;- renderDygraph({

# We want the user to be able to see the forecasted area, so let&amp;#39;s focus in on that 
# by truncating the view of the dygraph.
# We need to give the graph a start date and an end date. 
start_date &amp;lt;- tail(seq(input$dateRange[2], by = &amp;quot;-1 months&amp;quot;, length = 6), 1)
end_date &amp;lt;- tail(seq(input$dateRange[2], 
                     by = names(frequencyChoices[frequencyChoices == input$frequency]), 
                     length = input$periods), 1)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we will supply those date objects to a piped dygraphs chain, and that will be a wrap. Have a close look at the chunk below and spot where we again extract the name from the &lt;code&gt;input$dataSet&lt;/code&gt; name-value pair.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dygraph(combined_xts(), 
        # Name about to be extracted!
        main = paste(names(dataChoices[dataChoices==input$dataSet]), 
                     &amp;quot;: Historical and Forecast&amp;quot;, sep = &amp;quot;&amp;quot;)) %&amp;gt;%
  # Add the actual series.
  dySeries(&amp;quot;Actual&amp;quot;, label = &amp;quot;Actual&amp;quot;) %&amp;gt;%
  # Add the three forecasted series.
  dySeries(c(&amp;quot;Lo_95&amp;quot;, &amp;quot;Forecast&amp;quot;, &amp;quot;Hi_95&amp;quot;)) %&amp;gt;% 
  # A range selector to focus on the where historical data ends and 
  # foracated data begins.
  # Note the user can still use the range selector to zoom out if so desired.
  dyRangeSelector(dateWindow = c(start_date, end_date))
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That’s all for today! We’ve built an app that can be extended in many directions - more data set choices, an input selector so the user can choose different models, more visualizations - and in that sense it can serve as a template for ourselves and anyone that wants to build upon this work.&lt;/p&gt;
&lt;p&gt;This app also relies on and highlights one of the tremendous benefits of Quandl: the ability to import datasets from different sources and have them arrive in the IDE in a consistent format. This makes using Quandl with Shiny quite enjoyable after the initial skeleton is built. For example, if we or a colleague did want to change this app and substitute in different commodities, there would be no worry beyond the finding the right code on Quandl and adding another name-value pair to &lt;code&gt;dataChoices&lt;/code&gt;.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/04/21/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>March &#39;17 New Package Picks</title>
      <link>https://rviews.rstudio.com/2017/04/14/march-17-new-package-picks/</link>
      <pubDate>Fri, 14 Apr 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/04/14/march-17-new-package-picks/</guid>
      <description>
        
&lt;script src=&#34;/rmarkdown-libs/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-color.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-array.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-collection.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-format.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-dispatch.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-ease.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-interpolate.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-selection.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-scale.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-timer.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-transition.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-drag.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-path.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-shape.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-axis.v1.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3/d3-legend.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/d3-zoom-patched/d3-zoom-patched.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;/rmarkdown-libs/d3.lasso-plugin/lasso.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;/rmarkdown-libs/d3.lasso-plugin/lasso.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;/rmarkdown-libs/scatterD3/scatterD3.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-utils.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-setup.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-axes.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-dots.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-arrows.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-labels.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-lines.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-ellipses.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-legend.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-lasso.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3/scatterD3-exports.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;/rmarkdown-libs/scatterD3-binding/scatterD3.js&#34;&gt;&lt;/script&gt;

&lt;p&gt;Two hundred and sixteen new packages were added to CRAN in March. The following are my picks for the &lt;em&gt;Top Forty&lt;/em&gt;, organized into five categories: Bioscience, Data, Data Science, Statistics and Utilities.&lt;/p&gt;
&lt;div id=&#34;bioscience&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Bioscience&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/BioInstaller/index.html&#34;&gt;BioInstaller&lt;/a&gt; v0.0.3: Provides tools to install and download massive bioinformatics analysis software and database, such as NGS analysis tools with its required database or/and reference genome.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/DSAIDE/index.html&#34;&gt;DSAIDE&lt;/a&gt; v0.4.0: Provides a collection of Shiny Apps that allow users to simulate and explore infectious disease transmission. The &lt;a href=&#34;https://cran.r-project.org/web/packages/DSAIDE/vignettes/DSAIDE.html&#34;&gt;vignette&lt;/a&gt; will get you started.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/treespace/index.html&#34;&gt;treespace&lt;/a&gt; v1.0.0: Provides tools for the exploration of distributions of phylogenetic trees. This package includes a Shiny interface which can be started from R. There are vignettes for &lt;a href=&#34;https://cran.r-project.org/web/packages/treespace/vignettes/DengueVignette.html&#34;&gt;Dengue trees&lt;/a&gt;, &lt;a href=&#34;https://cran.r-project.org/web/packages/treespace/vignettes/TransmissionTreesVignette.html&#34;&gt;Transmission trees&lt;/a&gt;, and for exploring &lt;a href=&#34;https://cran.r-project.org/web/packages/treespace/vignettes/introduction.html&#34;&gt;landscapes of phylogenetic trees&lt;/a&gt;. The following plot from the vignette shows clusters of similar trees.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(treespace)
data(woodmiceTrees)
wm.res &amp;lt;- treespace(woodmiceTrees,nf=3)
wm.groves &amp;lt;- findGroves(wm.res, nclust=6)
plotGrovesD3(wm.groves)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;htmlwidget-6f18b5689440fa114559&#34; style=&#34;width:672px;height:480px;&#34; class=&#34;scatterD3 html-widget&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-6f18b5689440fa114559&#34;&gt;{&#34;x&#34;:{&#34;data&#34;:{&#34;x&#34;:[-0.994915614079129,-0.613678626917784,2.6667063130703,-13.6081153840016,2.19796507262781,3.60128203945996,-7.93464330242989,-0.601509902833136,-0.994915614079123,-0.601509902833136,-0.607150138418815,10.3943189332891,-8.22061660863031,-0.542706411478826,3.33541847941513,-0.043828098018826,-0.164629339023312,2.79080622437025,10.5466992537476,-0.611741178555835,3.57629422667165,9.6450605977335,3.87015775914438,-0.926024164827251,-1.2190898967413,2.4723857807866,-8.86243680646928,-1.21908989674129,-14.5730155701834,-13.602475148416,0.917863183050823,2.27894083741,2.28568544942178,-15.7748658745841,2.1492025394282,-0.790924629423665,12.7908135541976,0.944271832856846,-1.24839432652649,3.98230290310848,-1.01426319128175,2.01968513715778,2.67234654865598,3.60013557723756,-0.360155109563769,3.37184987522406,0.252595301625625,3.36472290920032,6.40461224612179,-0.994699490566318,-9.42122752144957,2.66670631307031,-9.45007781913339,-0.607150138418815,13.1790840072057,1.82079944018017,-1.24928257943979,-0.994915614079122,2.43713839500106,-13.044572686349,-15.9705489873276,-0.913373605366738,-13.6310955663375,3.64770068321681,0.668865915945599,8.14682718932421,13.4934309468058,4.04346690730909,2.2791569609228,-0.580632735597668,2.36612308170806,5.33313046919023,-0.994915614079123,11.0665629950681,-1.00840683218326,4.76538085706121,1.4438114263851,-0.171393662122702,2.02621362565675,-8.75385363504267,-0.858828154723405,-0.330268540830038,3.90067192022295,-0.0730717036886937,-16.5286674300406,-0.994915614079122,2.4723857807866,-9.65081856527717,-0.335908776415717,-0.796564865009345,-0.542706411478826,1.0492923610008,-1.21908989674129,-15.6745883154345,0.0979934237349428,-9.34792446440201,-0.437013152012128,2.27241234891102,-0.17689227089257,0.955121246501657,12.8975581653797,5.51089790555852,-10.4680320213257,-0.0399993481969869,9.52808714143766,3.5891133153753,4.42342442747862,0.04726565910757,-1.25417131433135,2.3611288897358,2.27894083741,-9.02693355729029,2.07898006954062,3.87668624764336,-6.4615827644661,2.03185386124243,1.82035414418588,-0.994915614079123,-1.01426319128175,3.37749011080974,0.199097799331354,-0.172281915035997,-1.00862295569607,4.15243988951517,-1.00840683218326,2.28458107299568,-0.607150138418815,-0.519052641259981,2.08128395756897,-16.5601837313279,2.46688265557635,-9.05280962299188,3.48076661737389,-0.995803866992419,-0.988171002067342,4.03546615887711,-0.994915614079123,-1.32470655220642,-0.989275378493443,3.56866136174658,-0.607150138418815,-7.66836564572728,-0.335908776415717,6.72470221778202,-0.27737989822945,-0.633026204120414,2.84248353506267,0.0979934237349427,2.92888779742133,3.20320883731573,-0.335908776415717,2.87234652407254,4.32578048491479,-1.25417131433135,2.83684329947699,-1.00751857926997,-0.915013358974152,3.57540597375836,-0.989275378493444,-0.707126558298265,-0.712766793883944,2.26633787221915,3.5888971918625,-1.01180587891182,-9.25652460111788,2.33076992578286,-0.165035101165791,3.30290284183795,-0.994699490566318,-16.2186567440298,3.5888971918625,-0.982530766481663,9.52808714143766,-0.606100942970156,2.73656237720091,3.46106473819439,2.27894083741,3.63680350037365,2.4723857807866,8.14682718932421,2.27894083741,-0.995803866992419,-9.25088436553221,0.859657106490925,0.774749830581254,0.04726565910757,-15.8890069786153,0.404970591334759,2.42557261667579,-0.613678626917791,-0.607013028043388,-0.919902093865714,2.28458107299568,-0.607150138418815,-0.765676710838193,4.14679965392949,-13.1809002016393,12.8975581653797,4.26288720150493,2.02621362565675,3.36367420397476],&#34;y&#34;:[-1.36296405257431,-1.0143380748759,4.21882824322934,1.85395115102287,4.17637909087138,4.86461034763142,-16.009575686826,-1.02771387775047,-1.36296405257431,-1.02771387775047,-1.02766987185401,-0.50552388611458,-10.0515267421666,-1.07229905286387,4.15752547173998,2.76392139550187,2.59796872098458,4.93883384448699,-10.7625404554933,-2.21247979854658,4.87226502578944,-9.5088708745062,3.32153776588015,-0.842513536381463,-0.716141175163109,-7.16104731132083,5.75437287564331,-0.716141175163109,-1.7069313395939,1.85390714512642,4.8987315359459,3.88353406250903,5.61969323330277,0.344365695407378,-14.4171273048538,-0.501442487250261,-9.6000449103967,1.03726886777004,-0.33393376356846,3.46374535755798,-1.35535338031275,4.91950411344246,4.21878423733287,7.13159940553585,-0.00302341316305915,5.01212399682195,-13.0610240652768,3.77531806014533,7.01232473326826,0.386526915197534,3.75962479695718,4.21882824322933,-11.8666109777134,-1.02766987185401,-8.32290371040569,2.52086549795982,-0.320645972486814,-1.36296405257431,4.62733018857611,3.8619430148942,-1.58401124473219,-1.37092740080123,-1.87858215341395,3.08391000762073,-1.19130284875386,-0.939160305549965,-9.99053252948651,5.96476384086601,5.63302503028087,-1.03141128116272,3.87552670838565,7.5655093012157,-1.36296405257431,-11.1843323318248,0.394093581562641,6.98752111471012,1.37775884921857,1.22975877872164,4.90617231646436,6.55363566239471,-1.1898855504877,0.868592373260222,6.09901634763347,1.2290930557728,0.146376109093674,-1.36296405257431,-7.16104731132083,-11.8099177019773,0.868636379156678,-0.501398481353804,-1.07229905286387,1.43585335420713,-0.716141175163109,-1.76388587914128,-0.23437411826138,-3.78957669060228,0.645071817193465,3.89686585948713,2.27313496228741,1.1554629700066,-9.37652435432995,8.34207063093772,4.70275523659972,-5.51421132484612,-8.2299588005646,4.87798615050598,6.18643823118439,0.0191206331844139,-0.326994001640874,-7.3165426940803,3.88353406250902,4.08158718069937,-7.49629748614467,3.30820596890205,1.9385779426291,4.9061283105679,1.76288229528141,-1.36296405257431,-1.35535338031275,5.0120799909255,-0.0108095562981677,1.24304656980329,-1.3553973862092,5.13648704660545,0.394093581562642,3.88349005661257,-1.02766987185401,-1.36622147874601,4.52661553061152,0.167362584229802,-7.16806857752342,4.10252964993904,-10.8783948870456,-1.34967626149266,0.373195118219431,3.41920418834103,-1.36296405257431,-0.871680563819035,-1.36300805847077,3.14939364607734,-1.02766987185401,-1.0051396096495,0.868636379156678,-2.10228430818339,0.0359583960557165,-1.00672740261434,5.89152592638034,-0.23437411826138,0.461240469186375,-9.87333975241742,0.868636379156678,-8.00759724325873,4.51980695910259,-0.326994001640875,5.8915699322768,0.380805790480995,-1.35124757466906,4.88555281687109,-1.36300805847077,-1.18325326640639,-1.18320926050994,5.62730390556433,3.12849518273413,-1.36839184423488,-11.4879553182351,4.29529384801837,-1.92883606503872,4.00946413995936,0.386526915197535,-0.0288756124843536,3.12849518273413,0.373151112322974,-8.2299588005646,-2.21252380444303,4.19946765707951,7.74251598858856,3.88353406250902,-10.4582816896664,-7.16104731132083,-0.939160305549963,3.88353406250902,-1.34967626149266,-11.4879993241316,0.931854402146931,10.0778445455006,0.0191206331844133,-1.59197459295911,1.73932530176124,-7.36117187509016,-1.01433807487591,-1.03473514395306,-1.35759560382312,3.88349005661257,-1.02766987185401,0.202085100647231,5.13653105250191,1.52547532730244,-9.37652435432995,8.19604761262773,4.90617231646436,7.45847251006686],&#34;col_var&#34;:[&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;3&#34;,&#34;2&#34;,&#34;4&#34;,&#34;5&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;4&#34;,&#34;5&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;6&#34;,&#34;1&#34;,&#34;4&#34;,&#34;6&#34;,&#34;4&#34;,&#34;1&#34;,&#34;1&#34;,&#34;6&#34;,&#34;3&#34;,&#34;1&#34;,&#34;3&#34;,&#34;3&#34;,&#34;1&#34;,&#34;2&#34;,&#34;2&#34;,&#34;3&#34;,&#34;6&#34;,&#34;1&#34;,&#34;6&#34;,&#34;1&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;2&#34;,&#34;2&#34;,&#34;2&#34;,&#34;1&#34;,&#34;2&#34;,&#34;6&#34;,&#34;4&#34;,&#34;4&#34;,&#34;1&#34;,&#34;3&#34;,&#34;2&#34;,&#34;5&#34;,&#34;1&#34;,&#34;6&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;3&#34;,&#34;3&#34;,&#34;1&#34;,&#34;3&#34;,&#34;4&#34;,&#34;1&#34;,&#34;4&#34;,&#34;6&#34;,&#34;2&#34;,&#34;2&#34;,&#34;1&#34;,&#34;2&#34;,&#34;2&#34;,&#34;1&#34;,&#34;6&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;3&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;3&#34;,&#34;1&#34;,&#34;6&#34;,&#34;5&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;3&#34;,&#34;1&#34;,&#34;3&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;1&#34;,&#34;6&#34;,&#34;2&#34;,&#34;3&#34;,&#34;6&#34;,&#34;6&#34;,&#34;4&#34;,&#34;4&#34;,&#34;1&#34;,&#34;1&#34;,&#34;6&#34;,&#34;2&#34;,&#34;3&#34;,&#34;6&#34;,&#34;4&#34;,&#34;3&#34;,&#34;2&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;3&#34;,&#34;6&#34;,&#34;3&#34;,&#34;6&#34;,&#34;1&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;3&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;2&#34;,&#34;6&#34;,&#34;1&#34;,&#34;6&#34;,&#34;4&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;4&#34;,&#34;1&#34;,&#34;5&#34;,&#34;2&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;3&#34;,&#34;4&#34;,&#34;1&#34;,&#34;6&#34;,&#34;1&#34;,&#34;2&#34;,&#34;2&#34;,&#34;2&#34;,&#34;6&#34;,&#34;6&#34;,&#34;4&#34;,&#34;2&#34;,&#34;1&#34;,&#34;5&#34;,&#34;1&#34;,&#34;4&#34;,&#34;1&#34;,&#34;3&#34;,&#34;1&#34;,&#34;6&#34;,&#34;1&#34;,&#34;1&#34;,&#34;1&#34;,&#34;2&#34;,&#34;1&#34;,&#34;1&#34;,&#34;4&#34;,&#34;3&#34;,&#34;6&#34;,&#34;4&#34;,&#34;2&#34;,&#34;2&#34;],&#34;key_var&#34;:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201]},&#34;settings&#34;:{&#34;x_log&#34;:false,&#34;y_log&#34;:false,&#34;labels_size&#34;:10,&#34;labels_positions&#34;:null,&#34;point_size&#34;:64,&#34;point_opacity&#34;:1,&#34;hover_size&#34;:1,&#34;hover_opacity&#34;:null,&#34;xlab&#34;:&#34;Axis 1&#34;,&#34;ylab&#34;:&#34;Axis 2&#34;,&#34;has_labels&#34;:false,&#34;col_lab&#34;:&#34;groups&#34;,&#34;col_continuous&#34;:false,&#34;colors&#34;:null,&#34;ellipses&#34;:false,&#34;ellipses_data&#34;:[],&#34;symbol_lab&#34;:&#34;symbol_var&#34;,&#34;size_range&#34;:[10,300],&#34;size_lab&#34;:&#34;NULL&#34;,&#34;opacity_lab&#34;:&#34;NULL&#34;,&#34;unit_circle&#34;:false,&#34;has_color_var&#34;:true,&#34;has_symbol_var&#34;:false,&#34;has_size_var&#34;:false,&#34;has_opacity_var&#34;:false,&#34;has_url_var&#34;:false,&#34;has_legend&#34;:true,&#34;has_tooltips&#34;:true,&#34;tooltip_text&#34;:null,&#34;has_custom_tooltips&#34;:false,&#34;click_callback&#34;:null,&#34;zoom_callback&#34;:null,&#34;fixed&#34;:false,&#34;legend_width&#34;:150,&#34;left_margin&#34;:30,&#34;html_id&#34;:&#34;scatterD3-NCAIFFXD&#34;,&#34;xlim&#34;:null,&#34;ylim&#34;:null,&#34;x_categorical&#34;:false,&#34;y_categorical&#34;:false,&#34;menu&#34;:true,&#34;lasso&#34;:false,&#34;lasso_callback&#34;:null,&#34;dom_id_reset_zoom&#34;:&#34;scatterD3-reset-zoom&#34;,&#34;dom_id_svg_export&#34;:&#34;scatterD3-svg-export&#34;,&#34;dom_id_lasso_toggle&#34;:&#34;scatterD3-lasso-toggle&#34;,&#34;transitions&#34;:false,&#34;axes_font_size&#34;:&#34;100%&#34;,&#34;legend_font_size&#34;:&#34;100%&#34;,&#34;caption&#34;:null,&#34;lines&#34;:{&#34;slope&#34;:[0,null],&#34;intercept&#34;:[0,0],&#34;stroke_dasharray&#34;:[5,5]},&#34;hashes&#34;:[]}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Data&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/cropdatape/index.html&#34;&gt;cropdatape&lt;/a&gt; v1.0.0: Provides access to data from the &lt;a href=&#34;http://siea.minagri.gob.pe/siea/?q=publicaciones/anuarios-estadisticos&#34;&gt;Agricultural Ministry of Peru&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/rdataretriever/index.html&#34;&gt;rdataretriever&lt;/a&gt; v1.0.0: Provides R access to the &lt;a href=&#34;http://data-retriever.org/&#34;&gt;Data Retriever&lt;/a&gt; command line interface that automates the tasks of finding, downloading, and cleaning public datasets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/rnaturalearth/index.html&#34;&gt;rnaturalearth&lt;/a&gt; v0.1.0: Provides functions to fetch &lt;a href=&#34;http://www.naturalearthdata.com/&#34;&gt;Natural Earth&lt;/a&gt; map data. There is an &lt;a href=&#34;https://cran.r-project.org/web/packages/rnaturalearth/vignettes/rnaturalearth.html&#34;&gt;introduction&lt;/a&gt; and a &lt;a href=&#34;https://cran.r-project.org/web/packages/rnaturalearth/vignettes/what-is-a-country.html&#34;&gt;vignette&lt;/a&gt; on working with countries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/ropercenter/index.html&#34;&gt;ropercenter&lt;/a&gt; v0.1.0: Provides registered users with programmatic, reproducible access to data sets from The &lt;a href=&#34;https://ropercenter.cornell.edu&#34;&gt;Roper Center for Public Opinion Research&lt;/a&gt;, which maintains the largest archive of public opinion data in existence. The &lt;a href=&#34;https://cran.r-project.org/web/packages/ropercenter/vignettes/ropercenter-vignette.htm&#34;&gt;vignette&lt;/a&gt; shows how to get started.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/statsgrokse/index.html&#34;&gt;statsgrokse&lt;/a&gt; v 0.1.4: Provides an API for the server containing &lt;a href=&#34;http://stats.grok.se/&#34;&gt;Wikipedia Page View Statistics&lt;/a&gt; for the years 2008 to 2015.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/ukds/index.html&#34;&gt;ukds&lt;/a&gt; v0.1.0: Enables reproducible, programmatic retrieval of datasets from the &lt;a href=&#34;https://www.ukdataservice.ac.uk&#34;&gt;UK Data Service&lt;/a&gt;. The &lt;a href=&#34;https://cran.r-project.org/web/packages/ukds/vigne&#34;&gt;vignette&lt;/a&gt; shows how to setup and use it.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;data-science&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Data Science&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/anomalyDetection/index.html&#34;&gt;anomalyDetection&lt;/a&gt; v0.1.1: Implements procedures to aid in detecting network log anomalies. The &lt;a href=&#34;https://cran.r-project.org/web/packages/anomalyDetection/vignettes/Introduction.html&#34;&gt;vignette&lt;/a&gt; provides examples.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/kerasR/index.html&#34;&gt;kerasR&lt;/a&gt; v0.4.1: Provides an interface to the &lt;a href=&#34;https://keras.io/&#34;&gt;Keras&lt;/a&gt; Deep Learning Library, which provides specifications for describing dense neural networks, convolution neural networks (CNN), and recurrent neural networks (RNN) running on top of either &lt;a href=&#34;https://www.tensorflow.org/&#34;&gt;TensorFlow&lt;/a&gt; or &lt;a href=&#34;http://deeplearning.net/software/theano/&#34;&gt;Theano&lt;/a&gt;. The &lt;a href=&#34;https://cran.r-project.org/web/packages/kerasR/vignettes/introduction.html&#34;&gt;vignette&lt;/a&gt; contains examples.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/modeval/index.html&#34;&gt;modeval&lt;/a&gt; v0.1.2: Allows users to easily compare multiple classifications models built with caret functions for small data sets. The &lt;a href=&#34;https://cran.r-project.org/web/packages/modeval/vignettes/modeval.html&#34;&gt;vignette&lt;/a&gt; provides examples.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-13-march-17-new-package-picks_files/modeval.png&#34; /&gt;

&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/supc/index.html&#34;&gt;supc&lt;/a&gt; v0.1: Implements the self-updating process clustering algorithms proposed in &lt;a href=&#34;doi:10.1080/00949655.2015.1049605&#34;&gt;Shiu and Chen&lt;/a&gt;. The &lt;a href=&#34;https://cran.r-project.org/web/packages/supc/vignettes/supc.html&#34;&gt;vignette&lt;/a&gt; contains examples.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/tensorflow/index.html&#34;&gt;tensorflow&lt;/a&gt; v0.7: Provides an interface to &lt;a href=&#34;https://www.tensorflow.org&#34;&gt;TensorFlow&lt;/a&gt;, an open-source software library for numerical computation using data flow graphs.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;statistics&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Statistics&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/frailtyEM/index.html&#34;&gt;frailtyEM&lt;/a&gt; v0.5.4: Contains functions for fitting shared frailty models with a semi-parametric baseline hazard using the Expectation-Maximization algorithm. The &lt;a href=&#34;https://cran.r-project.org/web/packages/frailtyEM/vignettes/frailtyEM_manual.pdf&#34;&gt;vignette&lt;/a&gt; explains the math.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/FRK/index.html&#34;&gt;FRK&lt;/a&gt; v0.1.1: Provides functions to build, fit and predict spatial random effects, fixed rank kriging models with large datasets. The &lt;a href=&#34;https://cran.r-project.org/web/packages/FRK/vignettes/FRK_intro.pdf&#34;&gt;vignette&lt;/a&gt; introduces the theory and shows some examples.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/hmi/index.html&#34;&gt;hmi&lt;/a&gt; v0.6-3: Allows users to build single-level and multilevel imputation models using functions provided, or functions from the mice and MCMCglmm packages. There is a &lt;a href=&#34;https://cran.r-project.org/web/packages/hmi/vignettes/my-vignette.html&#34;&gt;vignette&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/margins/index.html&#34;&gt;margins&lt;/a&gt; v0.3.0: Ports Stata’s &lt;code&gt;margins&lt;/code&gt; command for calculating marginal (or partial) effects. There is an &lt;a href=&#34;https://cran.r-project.org/web/packages/margins/vignettes/Introduction.html&#34;&gt;introduction&lt;/a&gt;, a vignette on the &lt;a href=&#34;https://cran.r-project.org/web/packages/margins/vignettes/TechnicalDetails.pdf&#34;&gt;Technical Implementation Details&lt;/a&gt;, and a comparison with the &lt;a href=&#34;https://cran.r-project.org/web/packages/margins/vignettes/Stata.html&#34;&gt;Stata Command&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/mlrMBO/index.html&#34;&gt;mlrMBO&lt;/a&gt; v1.0.0: Provides a toolbox for Bayesian, model-based optimization. There is an &lt;a href=&#34;https://cran.r-project.org/web/packages/mlrMBO/vignettes/mlrMBO.html&#34;&gt;introduction&lt;/a&gt; and vignettes for &lt;a href=&#34;https://cran.r-project.org/web/packages/mlrMBO/vignettes/mixed_space_optimization.html&#34;&gt;Mixed Space Optimization&lt;/a&gt;, &lt;a href=&#34;https://cran.r-project.org/web/packages/mlrMBO/vignettes/noisy_optimization.html&#34;&gt;Noisy Optimization&lt;/a&gt;, and &lt;a href=&#34;https://cran.r-project.org/web/packages/mlrMBO/vignettes/parallelization.html&#34;&gt;Parallelization&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-13-march-17-new-package-picks_files/mlrMBO.png&#34; /&gt;

&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/MonteCarlo/index.html&#34;&gt;MonteCarlo&lt;/a&gt; v1.0.0: Simplifies Monte Carlo simulation studies by providing functions that automatically set up loops to run over parameter grids, parallelize the computations, and generate output in LaTeX tables. The &lt;a href=&#34;https://cran.r-project.org/web/packages/MonteCarlo/vignettes/MonteCarlo-Vignette.html&#34;&gt;vignette&lt;/a&gt; shows how to use it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/RankingProject/index.html&#34;&gt;RankingProject&lt;/a&gt; v0.1.1: Provides functions to generate plots and tables for comparing independently sampled populations. There is an &lt;a href=&#34;https://cran.r-project.org/web/packages/RankingProject/vignettes/intro.html&#34;&gt;introduction&lt;/a&gt; and a &lt;a href=&#34;https://cran.r-project.org/web/packages/RankingProject/vignettes/primer.pdf&#34;&gt;vignette&lt;/a&gt; that reproduces the figures from “A Primer on Visualizations for Comparing Populations, Including the Issue of Overlapping Confidence Intervals” by Wright, Klein, and Wieczorek (2017, The American Statistician, in press).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/rjmcmc/index.html&#34;&gt;rjmcmc&lt;/a&gt; v0.2.2: Provides functions to perform &lt;a href=&#34;doi:10.2307/2337340&#34;&gt;reversible-jump MCMC&lt;/a&gt; with the restriction introduced by &lt;a href=&#34;doi:10.1080/00031305.2013.791644&#34;&gt;Barker &amp;amp; Link&lt;/a&gt;. The &lt;a href=&#34;https://cran.r-project.org/web/packages/rjmcmc/vignettes/rjmcmcVignette.pdf&#34;&gt;vignette&lt;/a&gt; shows how to calculate posterior probabilities from the MCMC output.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;utilities&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Utilities&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/canvasXpress/index.html&#34;&gt;canvasXpress&lt;/a&gt; v1.5.2: Enables creation of visualizations using &lt;a href=&#34;http://canvasxpress.org&#34;&gt;CanvasXpress&lt;/a&gt;, a stand-alone JavaScript library for reproducible research. The &lt;a href=&#34;https://cran.r-project.org/web/packages/canvasXpress/vignettes/getting_started.html&#34;&gt;vignette&lt;/a&gt; shows how to get started.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/collapsibleTree/index.html&#34;&gt;collapsibleTree&lt;/a&gt; v0.1.4: Provides functions to build interactive Reingold-Tilford tree diagrams created using D3.js, where every node can be expanded and collapsed by clicking on it. There are some &lt;a href=&#34;https://adeelk93.github.io/collapsibleTree/&#34;&gt;examples&lt;/a&gt; on the GitHub site.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-13-march-17-new-package-picks_files/collapsibleTree.png&#34; /&gt;

&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/cronR/&#34;&gt;cronR&lt;/a&gt; v0.3.0: Allows users to schedule R scripts and processes on Unix/Linux systems, while &lt;a href=&#34;https://cran.r-project.org/web/packages/taskscheduleR/index.html&#34;&gt;taskscheduleR&lt;/a&gt; allows the same from Windows. See the &lt;a href=&#34;https://cran.r-project.org/web/packages/cronR/vignettes/cronR.html&#34;&gt;cronR vignette&lt;/a&gt; and the &lt;a href=&#34;https://cran.r-project.org/web/packages/taskscheduleR/vignettes/taskscheduleR.html&#34;&gt;taskscheduleR vignette&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/doctr/index.html&#34;&gt;doctr&lt;/a&gt; v0.2.0: Provides tools to help check the consistency and quality of a dataset. There are vignettes for &lt;a href=&#34;https://cran.r-project.org/web/packages/doctr/vignettes/doctr_compare.html&#34;&gt;Comparing Tables&lt;/a&gt;, &lt;a href=&#34;https://cran.r-project.org/web/packages/doctr/vignettes/doctr_diagnose.html&#34;&gt;Dataset Diagnostics&lt;/a&gt;, and &lt;a href=&#34;https://cran.r-project.org/web/packages/doctr/vignettes/doctr_examine.html&#34;&gt;EDA Automation&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/geojsonR/index.html&#34;&gt;geojsonR&lt;/a&gt; v1.0.1: Provides functions to process &lt;a href=&#34;https://en.wikipedia.org/wiki/GeoJSON&#34;&gt;GeoJson objects&lt;/a&gt;. The &lt;a href=&#34;https://cran.r-project.org/web/packages/geojsonR/vignettes/the_geojsonR_package.html&#34;&gt;vignette&lt;/a&gt; gives the details.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/ggedit/index.html&#34;&gt;ggedit&lt;/a&gt; v0.2.1: Provides an interactive layer and theme aesthetic editor for ggplot2. The &lt;a href=&#34;vhttps://metrumresearchgroup.github.io/ggedit/&#34;&gt;ggedit gitbook&lt;/a&gt; explains how to use it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/implyr/index.html&#34;&gt;implyr&lt;/a&gt; v0.1.0: Provides a SQL backend to dplyr for &lt;a href=&#34;https://impala.apache.org/&#34;&gt;Apache Impala&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/officer/index.html&#34;&gt;officer&lt;/a&gt; v0.1.0: Provides functions to manipulate &lt;a href=&#34;https://cran.r-project.org/web/packages/officer/vignettes/word.html&#34;&gt;Microsoft Word&lt;/a&gt; and &lt;a href=&#34;https://cran.r-project.org/web/packages/officer/vignettes/powerpoint.html&#34;&gt;Microsoft Powerpoint&lt;/a&gt; documents. This is a companion package to flextable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/flextable/index.html&#34;&gt;flextable&lt;/a&gt; v.1.0: Includes functions to create tables in Word, PowerPoint, and HTML documents. There is an &lt;a href=&#34;https://cran.r-project.org/web/packages/flextable/vignettes/overview.html&#34;&gt;overview&lt;/a&gt;, and vignettes for &lt;a href=&#34;https://cran.r-project.org/web/packages/flextable/vignettes/format.html&#34;&gt;explaining objects&lt;/a&gt; and &lt;a href=&#34;https://cran.r-project.org/web/packages/flextable/vignettes/layout.html&#34;&gt;table layout&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/pivottabler/index.html&#34;&gt;pivottabler&lt;/a&gt; v0.1.0: Allows users to create complex pivot tables and pivot tables with irregular layouts in R. There are multiple vignettes, including an &lt;a href=&#34;https://cran.r-project.org/web/packages/pivottabler/vignettes/introduction.html&#34;&gt;introduction&lt;/a&gt;, a &lt;a href=&#34;https://cran.r-project.org/web/packages/pivottabler/vignettes/styling.html&#34;&gt;styling guide&lt;/a&gt;, a &lt;a href=&#34;https://cran.r-project.org/web/packages/pivottabler/vignettes/shiny.html&#34;&gt;Shiny example&lt;/a&gt; and explanations of &lt;a href=&#34;https://cran.r-project.org/web/packages/pivottabler/vignettes/calculations.html&#34;&gt;calculations&lt;/a&gt; and &lt;a href=&#34;https://cran.r-project.org/web/packages/pivottabler/vignettes/datagroups.html&#34;&gt;data groups&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/Polychrome/index.html&#34;&gt;Polychrome&lt;/a&gt; v0.8.2: Provides tools for creating, viewing, and assessing qualitative palettes with many (20-30 or more) colors. There is a colorful &lt;a href=&#34;https://cran.r-project.org/web/packages/Polychrome/vignettes/polychrome.html&#34;&gt;vignette&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(Polychrome)
pal2 &amp;lt;- alphabet.colors(26)
rancurves(pal2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/post/2017-04-13-march-17-new-package-picks_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/RApiDatetime/index.html&#34;&gt;RApiDatetime&lt;/a&gt; v0.0.3: Provides a C-level API to allow packages to access C-level R date and datetime code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/Rcssplot/index.html&#34;&gt;Rcssplot&lt;/a&gt; v0.2.0.0: Provides tools to style plots with cascading style sheets. The &lt;a href=&#34;https://cran.r-project.org/web/packages/Rcssplot/vignettes/Rcssplot.pdf&#34;&gt;vignette&lt;/a&gt; shows how.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/reticulate/index.html&#34;&gt;reticulate&lt;/a&gt; v0.7: Implements an R interface to Python modules, classes, and functions. When calling into Python, R data types are automatically converted to their equivalent Python types. When values are returned from Python to R, they are converted back to R types. There is an &lt;a href=&#34;https://cran.r-project.org/web/packages/reticulate/vignettes/introduction.html&#34;&gt;overview&lt;/a&gt; and a vignette describing &lt;a href=&#34;https://cran.r-project.org/web/packages/reticulate/vignettes/arrays.html&#34;&gt;arrays in R and Python&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/shinyWidgets/index.html&#34;&gt;shinyWidgets&lt;/a&gt; v0.2.0: Provides custom input widgets for Shiny apps. See the &lt;a href=&#34;https://cran.r-project.org/web/packages/shinyWidgets/README.html&#34;&gt;README&lt;/a&gt; for examples.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2017-04-13-march-17-new-package-picks_files/shinyWidgets.png&#34; /&gt;

&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/shinyjqui/index.html&#34;&gt;shinyjqui&lt;/a&gt; v0.1.0: An extension to shiny that brings interactions and animation effects from the &lt;code&gt;jQuery UI&lt;/code&gt; library. There is an &lt;a href=&#34;https://cran.r-project.org/web/packages/shinyjqui/vignettes/introduction.html&#34;&gt;introduction&lt;/a&gt; and a &lt;a href=&#34;https://cran.r-project.org/web/packages/shinyjqui/vignettes/orderInput.html&#34;&gt;vignette&lt;/a&gt; with examples.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&#34;https://cran.r-project.org/web/packages/valaddin/index.html&#34;&gt;valaddin&lt;/a&gt; v0.1.0: Provides tools to transform functions into functions with input validation checks, in a manner suitable for both programmatic and interactive use. The &lt;a href=&#34;https://cran.r-project.org/web/packages/valaddin/vignettes/valaddin.html&#34;&gt;vignette&lt;/a&gt; shows how.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/04/14/march-17-new-package-picks/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Solving Data Science&#39;s First Mile Problem</title>
      <link>https://rviews.rstudio.com/2017/04/07/solving-data-sciences-first-mile-problem/</link>
      <pubDate>Fri, 07 Apr 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/04/07/solving-data-sciences-first-mile-problem/</guid>
      <description>
        
&lt;!-- BLOGDOWN-HEAD --&gt;
&lt;!-- /BLOGDOWN-HEAD --&gt;

&lt;!-- BLOGDOWN-BODY-BEFORE --&gt;
&lt;!-- /BLOGDOWN-BODY-BEFORE --&gt;
&lt;p&gt;At &lt;a href=&#34;https://data.world/&#34;&gt;data.world&lt;/a&gt;, we are out to solve the “first mile problem of data science”: helping people obtain and understand the data sets they need. Everybody starts here whether they are analyzing their fantasy football league or working on the Zika pandemic. But unfortunately, as Professor Eric Schwartz at the University of Michigan said to me recently: “for so many people, the first mile of data science is the last mile, because people just quit when they see the data.”&lt;/p&gt;
&lt;p&gt;We have begun by asking these two questions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;What if people who work on data projects could adopt the principles and processes of the open source community?&lt;/p&gt;
&lt;p&gt;We believe that with transparency, meritocracy and a bottoms-up approach to knowledge management, the world could benefit from the understanding of those who came before them.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What if we could democratize the semantic web and linked data concepts?&lt;/p&gt;
&lt;p&gt;Tim Berners-Lee, the creator of HTML and inventor of the hyperlink, has envisioned a future where the web links not only documents, but data too. There’s tremendous power in this vision for linked data across the web. Unfortunately, these concepts are obtuse and not accessible to most people working on data (we are data people after all, and not knowledge engineers).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;One group that is using data.world to effectively solve their first mile problem is &lt;a href=&#34;http://datafordemocracy.org/&#34;&gt;Data for Democracy&lt;/a&gt;. This incredibly diverse group of over 1200 people aims “to be an inclusive community for data scientists and technologists to volunteer and collaborate on projects that make a positive impact on society”. Their &lt;a href=&#34;https://data.world/data4democracy/drug-spending&#34;&gt;Medicare/Medicaid drug spending project&lt;/a&gt; makes particularly good use of the unique features of data.world datasets by including files of many different formats, &lt;a href=&#34;https://data.world/data4democracy/drug-spending/query/94dfc980-5bb7-4190-8696-a40a6e724bfb&#34;&gt;publishing queries&lt;/a&gt;, and then &lt;a href=&#34;https://jenniferthompson.shinyapps.io/shinydashboard-medicared/&#34;&gt;building dashboards&lt;/a&gt; using Shiny against the normalized data queried from our &lt;a href=&#34;https://docs.data.world/documentation/api/&#34;&gt;API&lt;/a&gt;. Now their first mile work is captured in an accessible format with clear context, so others will be able to easily and quickly build on it in the future.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/post/2017-04-07-solving-data-science_files/dataworld.png&#34; /&gt; .&lt;/p&gt;
&lt;p&gt;Context is king in so many aspects of life, and it’s especially true when you’re working with data. data.world helps you understand the data you are working with by providing a context for datasets that quickly gets you to the who, what, where, when, why and how of the data. Once you understand the data, we want you to get that data into your tools as quickly as possible with our &lt;a href=&#34;https://docs.data.world/&#34;&gt;APIs and SDKs&lt;/a&gt;, and then get any analysis you’ve done back into data.world for further distribution and discussion.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Who&lt;/strong&gt; - data.world shows you who the contributors are on a dataset, who has liked it and who is commenting. This allows you to see who is working on this data or project, and what other things they work on by browsing their profiles. You can also request to be a contributor if you have something to add!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What&lt;/strong&gt; - What is this data, what can it be used for, what have people done with this data? Published queries, exploratory visualizations, shared R markdown and notebooks, documentation and analysis all help answer these three critical questions. Of course, you can use the discussions feature to ask the owners and contributors questions about the data as well.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Where&lt;/strong&gt; - Where did this data come from? In the world of data, this is intrinsically tied to “who.” In addition to getting all the social context of “who” from our rich profiles, we encourage people to cite the sources of their data in the dataset summary or in further documentation (PDF or Markdown) included in the dataset. This helps users understand the provenance of the data.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When&lt;/strong&gt; - When has this data changed and when has it been used? With data.world, you can tell when the data was last updated, when analyses were done, and whether people are actively discussing it. All this helps to determine if the data is suitable to your purpose and, if you’re new to a data, if it still fits in the context of the question you’re asking.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why&lt;/strong&gt; - Why does this data answer my questions or tell the story it does? Why should I use or trust this data? We love it when people upload a lot more than just the data and code. We specifically allow people to add images and documentation to their datasets to tell their data’s story.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How&lt;/strong&gt; - How do I work with this data? How is my data being used by others? With our shareable and publishable queries and the ability to share source code alongside the raw data, you don’t have to recreate work that others have done. If you’re a dataset owner, providing the code that operates on the data or sharing a query that cleans or joins the data in interesting ways provides other people a jumping-off point or a way to reproduce your research and test your findings easily.&lt;/p&gt;
&lt;p&gt;In a follow-up to this article, we’ll show you how to use our &lt;a href=&#34;https://www.youtube.com/watch?v=VELntRdDtJ4&#34;&gt;R SDK&lt;/a&gt; along with our data normalization features to discover, join and add features to data in RStudio. In the interim, if you want to jump in and start using data.world to power your R projects and analyses the way that Data for Democracy is, I recommend checking out this &lt;a href=&#34;https://data.world/jonloyens/intermediate-data-world&#34;&gt;tutorial&lt;/a&gt;, in which we show how to link data from the Washington Post with data discovered in data.world using RStudio.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;About the Author&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Jon Loyens is the Co-Founder and Chief Product Officer of data.world. In a past life, he was the VP of Engineering for Traveler Products at HomeAway, and before that, a VP of Engineering and Director of the Labs group at Bazaarvoice. As a long-time technology executive in Austin, he has seen the rise of the trends towards data and analytics as a democratizing force. Jon brought A/B testing and data-driven product management to Bazaarvoice, and massively expanded the data programs at HomeAway. Jon introduced GitHub to Bazaarvoice and made OSS contribution a major part of their culture. He’s seen the benefits of openness and transparency in software and, at data.world, is bringing the same benefits to open data.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/04/07/solving-data-sciences-first-mile-problem/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Reproducible Finance with R: Sector Correlations Shiny App</title>
      <link>https://rviews.rstudio.com/2017/02/03/reproducible-finance-with-r-sector-correlations-shiny-app/</link>
      <pubDate>Fri, 03 Feb 2017 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2017/02/03/reproducible-finance-with-r-sector-correlations-shiny-app/</guid>
      <description>
        
&lt;!-- BLOGDOWN-HEAD --&gt;
&lt;!-- /BLOGDOWN-HEAD --&gt;

&lt;!-- BLOGDOWN-BODY-BEFORE --&gt;
&lt;!-- /BLOGDOWN-BODY-BEFORE --&gt;
&lt;p&gt;In a &lt;a href=&#34;https://www.rstudio.com/rviews/2017/01/18/reproducible-finance-with-r-sector-correlations/&#34;&gt;previous post&lt;/a&gt;, we built an R Notebook that pulled in data on sector ETFs and allowed us to calculate the rolling correlation between a sector ETF and the S&amp;amp;P 500 ETF, whose ticker is SPY. Today, we’ll wrap that into a Shiny app that allows the user to choose a sector, a returns time period such as ‘daily’ or ‘weekly’, and a rolling window. For example, if a user wants to explore the 60-day rolling correlation between the S&amp;amp;P 500 and an energy ETF, our app will show that. As is customary, we will use the flexdashboard format and reuse as much as possible from our Notebook.&lt;/p&gt;
&lt;p&gt;The final app is &lt;a href=&#34;http://colorado.rstudio.com:3939/content/264/&#34;&gt;here&lt;/a&gt;, with the code available in the upper right-hand corner. Let’s step through this script.&lt;/p&gt;
&lt;p&gt;The first code chunk is where we do the heavy lifting in this app. We will build a function that takes as parameters an ETF ticker, a returns period, and a window of time, and then calculates the desired rolling correlation between that ETF ticker and SPY.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(flexdashboard)
library(quantmod)
library(dygraphs)
library(dplyr)

# A function to build an xts object to hold both sector and index returns.
sector_correlations &amp;lt;- function(sector, period = &amp;quot;weekly&amp;quot;, window = 10) {

# Make a data frame of the sector and S&amp;amp;P 500 ETF.
etf_ticker_sector &amp;lt;- data_frame(c(sector, &amp;quot;SPY&amp;quot;))

colnames(etf_ticker_sector) &amp;lt;- &amp;quot;tickers&amp;quot;

# Use getSymbols and Ad to get adjusted prices.

symbols &amp;lt;- getSymbols(etf_ticker_sector$tickers, auto.assign = TRUE, warnings = FALSE)

etf_prices &amp;lt;- do.call(merge, lapply(symbols, function(x) Ad(get(x))))

# We want log returns by the period chosen by the user. 

etf_returns &amp;lt;- do.call(merge, lapply(etf_prices, 
                                     function(x) periodReturn(x, period = period, type = &amp;#39;log&amp;#39;)))

# Create one xts object we can pass to rollapply.
merged_xts &amp;lt;- merge(etf_returns[, 1], etf_returns[, 2])

merged_xts$rolling_cor &amp;lt;- rollapply(merged_xts, window, 
                                         function(x) cor(x[, 1], x[, 2], use = &amp;quot;pairwise.complete.obs&amp;quot;), 
                                         by.column = FALSE)
# We care about the name because it will be displayed in the dygraph when a user hovers.

names(merged_xts) &amp;lt;- c(paste(sector, &amp;quot;Returns&amp;quot;, sep = &amp;quot;&amp;quot;), &amp;quot;SPY Returns&amp;quot;, paste(sector, &amp;quot;/SPY Correlation&amp;quot;, sep = &amp;quot;&amp;quot;))

    
assign(&amp;quot;sector_correlations&amp;quot;, merged_xts, .GlobalEnv)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That function uses &lt;code&gt;getSymbols()&lt;/code&gt; to pull in prices and &lt;code&gt;periodReturns()&lt;/code&gt; to convert to log returns, either daily, weekly or monthly. Then we merge into one xts object and calculate rolling correlations, depending on the window parameter. It should look familiar from the Notebook, but honestly, the transition from the previous Notebook to this code chunk wasn’t as smooth as would be ideal. I broke this into two functions in the Notebook, but thought it flowed more smoothly as one function in the app since I don’t need the intermediate results stored in a persistent way. Combining the two functions wasn’t difficult, but it did break the reproducible chain in a way that I don’t love. In the real world, I would (and, in my IDE, I did) refactor the Notebook to line up with the app better. Enough self-shaming, back to it.&lt;/p&gt;
&lt;p&gt;Next, we need to create a sidebar where our users can select a sector, a returns period and a rolling window. Nothing fancy here, but one thing to note is how we use &lt;code&gt;selectInput&lt;/code&gt; to translate from the sector to the ETF ticker symbol. This means our users don’t have to remember those three-letter codes; they just choose the name of the desired sector from a drop-down menu.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;helpText(&amp;quot;Choose a sector&amp;quot;)

# Don&amp;#39;t make the user memorize the ETF ticker symbols! 
# Let them choose the intuitive sector name and then translate to the 
# ticker symbol in the background.

fluidRow(
  column(9,
  selectInput(&amp;quot;sector&amp;quot;, &amp;quot;Sector ETF&amp;quot;,
                c(
                  &amp;quot;Energy&amp;quot; = &amp;quot;XLE&amp;quot;,
                  &amp;quot;Financials&amp;quot; = &amp;quot;XLF&amp;quot;,
                  &amp;quot;Health Care&amp;quot; = &amp;quot;XLV&amp;quot;,
                  &amp;quot;Industrials&amp;quot; = &amp;quot;XLI&amp;quot;, 
                  &amp;quot;Materials&amp;quot; = &amp;quot;XLB&amp;quot;, 
                  &amp;quot;Technology&amp;quot; = &amp;quot;XLK&amp;quot;, 
                  &amp;quot;Utilities&amp;quot; = &amp;quot;XLU&amp;quot;,
                  &amp;quot;Cons Discretionary&amp;quot; = &amp;quot;XLY&amp;quot;, 
                  &amp;quot;Cons Staples&amp;quot; = &amp;quot;XLP&amp;quot;)))
)  

helpText(&amp;quot;Choose a returns time period and a rolling window&amp;quot;)

fluidRow(
  column(7,
  selectInput(&amp;quot;period&amp;quot;, &amp;quot;Time Period&amp;quot;, c(&amp;quot;daily&amp;quot;, &amp;quot;weekly&amp;quot;, &amp;quot;monthly&amp;quot;))),
  column(7,
  numericInput(&amp;quot;window&amp;quot;, &amp;quot; Rolling Window&amp;quot;, 10, min = 5, max = 50, step = 5))
)

# I like giving the user the option of whether to display the mean, min and max. 
# It doesn&amp;#39;t make a huge difference, of course, but at least enables the user to 
# notice the lines more consistently. 
checkboxInput(&amp;quot;max&amp;quot;, label = &amp;#39;Display Max Rolling Correlation&amp;#39;, value = FALSE)
checkboxInput(&amp;quot;mean&amp;quot;, label = &amp;#39;Display Mean Rolling Correlation&amp;#39;, value = FALSE)
checkboxInput(&amp;quot;min&amp;quot;, label = &amp;#39;Display Min Rolling Correlation&amp;#39;, value = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Have a close look at the last three lines of code in that chunk. These are a new addition that let the user determine if the mean, max and/or min rolling correlation should be included in the dygraph. We haven’t built any way of calculating those values yet, but we will shortly. This is the UI component.&lt;/p&gt;
&lt;p&gt;Those three lines of code create checkboxes and are set to default as FALSE, meaning they won’t be plotted unless the user chooses to do so. I wanted to force the user to actively click a control to include these, but that’s a purely stylistic choice. Perhaps you don’t want to give them a choice at all here?&lt;/p&gt;
&lt;p&gt;Next, we create our reactive values that will form the substance of this app. First, we need to calculate and store an object of rolling correlations, and we’ll use a reactive that passes user inputs to our &lt;code&gt;sector_correlations&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Then, we build reactive objects to store mean, minimum and maximum rolling correlations. These values will help contextualize our final dygraph.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Build our correlation time series object here
# so we can access it throughout the rest of the app.

sector_correlation &amp;lt;- reactive({
  sector_corr &amp;lt;- sector_correlations(input$sector, input$period, input$window)
  sector_corr[, 3]
})

# Let&amp;#39;s calculate mean, minimum and maximum rolling correlations. 
# We&amp;#39;ll use these on the graph and in the value boxes.
avg &amp;lt;- reactive({ 
  avg &amp;lt;- round(mean(sector_correlation(),  na.rm=T), 2)
  })
mini &amp;lt;- reactive({
  mini &amp;lt;- round(min(sector_correlation(),  na.rm=T), 2)
  })
maxi &amp;lt;- reactive({
  maxi &amp;lt;- round(max(sector_correlation(),  na.rm=T), 2)
  })&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At this point, we have done some good work: built a function to calculate rolling correlations based on user input, built a sidebar to take that user input, and coded reactives to hold the values and some helpful statistics. The hard work is done, and really we did most of the hard work in the Notebook, where we toiled over the logic of arriving at this point. All that’s left now is to display this work in a compelling way. Dygraphs plus value boxes has worked in past; let’s stick with it!&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Dygraph time!

dygraphOutput(&amp;quot;dygraphCorrelation&amp;quot;)

output$dygraphCorrelation &amp;lt;- renderDygraph({
  
  dygraph(sector_correlation(), 
          main = paste(&amp;quot;rolling&amp;quot;, input$period, &amp;quot;correlation &amp;quot;, input$sector, &amp;quot;/SPY&amp;quot;, sep = &amp;quot; &amp;quot;)) %&amp;gt;% 
  # A new wrinkle that hasn&amp;#39;t been included in previous flexdashboards: let the user add lines to the 
  # dygraph.   
  dyLimit(if(input$mean == TRUE) {avg()}, color = &amp;#39;black&amp;#39;) %&amp;gt;% 
  dyLimit(if(input$min == TRUE) {mini()}, color = &amp;#39;red&amp;#39;) %&amp;gt;% 
  dyLimit(if(input$max == TRUE) {maxi()}, color = &amp;#39;blue&amp;#39;)
  
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That dygraph code should look familiar from the Notebook and previous posts, except we have added a little interactive feature. By including &lt;code&gt;if(input$mean == TRUE) {avg()}&lt;/code&gt;, we allow the user to change the graph by checking or unchecking the ‘mean’ input box in the sidebar. We are going to display this same information numerically in a value box, but the lines make this graph a bit more compelling.&lt;/p&gt;
&lt;p&gt;Speaking of those value boxes, they rely on the reactives we built above, but, unlike the graph lines, they are always going to be displayed. The user doesn’t have a choice here.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;valueBoxOutput(&amp;quot;approvalBox1&amp;quot;)
output$approvalBox1&amp;lt;-renderValueBox({
 
  # Display the mean we calculated in &amp;#39;avg&amp;#39; reactive function above.
  
  valueBox(value = avg(), icon = &amp;quot;fa-line-chart&amp;quot;, color = &amp;quot;primary&amp;quot;)
  
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, this just adds a bit of context to the graph. Note that the lines and the value boxes take their value from the same reactives. If we were to change those reactives, both UI components would be affected.&lt;/p&gt;
&lt;p&gt;Our job is done! This a simple but powerful app: the user can choose to see the 60-day rolling correlations between the S&amp;amp;P 500 and an energy ETF, or the 10-month rolling correlations between the S&amp;amp;P 500 and a utility ETF, etc. I played around with this a little bit and was surprised that the 10-week rolling correlation between the S&amp;amp;P 500 and health care stocks plunged in April of 2016. Someone smarter than I can probably explain, or at least hypothesize, as to why that happened.&lt;/p&gt;
&lt;p&gt;A closing thought about how this app might have been different: we are severely limiting what the user can do here, and intentionally so. The user can choose only from the sector ETFs that we are offering in the &lt;code&gt;selectInput&lt;/code&gt; dropdown. This is a sector correlations app, so I included only a few sector ETFs. But, we could just as easily have made this a &lt;code&gt;textInput&lt;/code&gt; and allowed the users to enter whatever ticker symbol struck their fancy. In that case, this would not longer be a sector correlations app; it would be a general stock correlations app. We could go even further and make this a general asset correlations app, in which case we would allow the user to select things like commodity, currency and housing returns and see how they correlate with stock market returns. Think about how that might change our data import logic and time series alignment.&lt;/p&gt;
&lt;p&gt;Thanks for reading, enjoy the app, happy coding, and see you next time!&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2017/02/03/reproducible-finance-with-r-sector-correlations-shiny-app/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Reproducible Finance with R: A Shiny ETF Map</title>
      <link>https://rviews.rstudio.com/2016/12/16/reproducible-finance-with-r-a-shiny-etf-map/</link>
      <pubDate>Fri, 16 Dec 2016 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2016/12/16/reproducible-finance-with-r-a-shiny-etf-map/</guid>
      <description>
        &lt;p&gt;In a &lt;a href=&#34;https://www.rstudio.com/rviews/2016/12/14/reproducible-finance-with-r-pulling-and-displaying-etf-data/&#34;&gt;previous post&lt;/a&gt;, we built an R Notebook that laid the groundwork for a Shiny app that allows users to graph country ETFs by clicking on a world map. In today&amp;rsquo;s Fun Friday post, we&amp;rsquo;ll charge forth to build that app, again using a flexdashboard so that we can stay in the Rmarkdown schema. Devoted readers of this blog know that I have a predilection for the Notebook-to-flexdashboard workflow, for reasons of efficiency and reproducibility.&lt;/p&gt;

&lt;p&gt;The final app is &lt;a href=&#34;http://colorado.rstudio.com:3939/Global-ETF-Map/&#34;&gt;here&lt;/a&gt;, with the code available in the upper right-hand corner. Let&amp;rsquo;s step through this script.&lt;/p&gt;

&lt;p&gt;In the first code chunk, we load the ‘etfData.RDat&amp;rsquo; file, the same file that we created in the dataGrab Notebook to save our shapefile of the world. After loading that file, we use the exact same code from the Notebook to construct our leaflet map.&lt;/p&gt;

&lt;p&gt;Next, we want to display that map in the first row of our flexdashboard. We will use ‘renderLeaflet&amp;rsquo;. Nothing fancy here.&lt;/p&gt;

&lt;p&gt;Now, we want to add the ability for the user to click a country and see the price history of that country&amp;rsquo;s ETF. This will require the following steps: (1) click a country, (2) pass the ETF ticker symbol to &lt;code&gt;getSymbols&lt;/code&gt;, (3) import the price data time series, and (4) display the time series using &lt;code&gt;dygraphs&lt;/code&gt;. All of this is going to be easy for us because of an important decision that we made when building our leaflet map object.&lt;/p&gt;

&lt;p&gt;Recall that we set &lt;code&gt;layerID = ticker&lt;/code&gt; in the view. This is part of the magic of the shapefile. It allows us to capture the ticker symbol associated with a country shape when a user clicks. Our ticker column is associated with our country longitudes and latitudes. In the code chunk below, we use an &lt;code&gt;observeEvent&lt;/code&gt; function to capture the ID of whatever shape a user clicks, and we set that ID to be the ticker.&lt;/p&gt;

&lt;p&gt;Now, we have the ticker in the ‘clickedCountry&amp;rsquo; reactive, and just need to pass it to &lt;code&gt;getSymbols&lt;/code&gt;. One important note: if a user clicks on a country with no ETF, that reactive object will be ‘NA&amp;rsquo; or null. The first step in the code chunk below is to validate the entry and, if it is null, let the user know that a country with no ETF has been clicked.&lt;/p&gt;

&lt;p&gt;To graph the resulting xts object, which we have named ‘etf&amp;rsquo;, we pass it to &lt;code&gt;dygraph&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Remember, there were two key components: setting &lt;code&gt;layerID = ticker&lt;/code&gt; and then capturing that &lt;code&gt;layerID&lt;/code&gt; using &lt;code&gt;observeEvent&lt;/code&gt; when a user clicks&lt;/p&gt;

&lt;p&gt;That&amp;rsquo;s it for building this app, but keep in mind: this interface need not be limited to country ETFs. We could wire this up to display currency prices, interest rates, labor force participation rates, or, say, the 10 best-performing stocks in a country. We could combine this map with the &lt;a href=&#34;https://www.rstudio.com/rviews/2016/11/18/reproducible-finance-with-r-a-sharpe-ratio-shiny-app/&#34;&gt;Sharpe Ratio app&lt;/a&gt;, so that a user could build his portfolio by clicking on different countries, selecting weightings to those countries, and then calculating the Sharpe Ratio. Instead of simply displaying a time series of prices, we could display the results of a forecasting model for each country. The nice thing is that once we have our template to use a map as an interface to data, the world is our playground.&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2016/12/16/reproducible-finance-with-r-a-shiny-etf-map/&#39;;&lt;/script&gt;
      </description>
    </item>
    
    <item>
      <title>Reproducible Finance with R: A Sharpe Ratio Shiny App</title>
      <link>https://rviews.rstudio.com/2016/11/18/reproducible-finance-with-r-a-sharpe-ratio-shiny-app/</link>
      <pubDate>Fri, 18 Nov 2016 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2016/11/18/reproducible-finance-with-r-a-sharpe-ratio-shiny-app/</guid>
      <description>
        &lt;p&gt;In this &lt;a href=&#34;/2016/11/09/reproducible-finance-with-r-the-sharpe-ratio/&#34;&gt;previous post&lt;/a&gt;, we used an R Notebook to grab the monthly return data on three stocks, build a portfolio, visualize portfolio performance, and calculate the Sharpe Ratio. The Notebook format emphasized reproducibility and reuse by other R coders.&lt;/p&gt;

&lt;p&gt;Today, we&amp;rsquo;ll convert that Notebook into a Shiny application that allows end users to build their own portfolios, and then calculate performance/Sharpe Ratio. Friday = fun day!&lt;/p&gt;

&lt;p&gt;Here is the &lt;a href=&#34;https://beta.rstudioconnect.com/content/2128/#sharpe-ratio&#34;&gt;link to the app&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Close readers of the source code for this app will see that it was built in an Rmarkdown file (with &lt;code&gt;output: flexdashboard::flexdashboard&lt;/code&gt; and &lt;code&gt;runtime: shiny&lt;/code&gt; added to the YAML header).&lt;/p&gt;

&lt;pre&gt;&lt;code class=&#34;language-yaml&#34;&gt;---
title: &amp;quot;Sharpe Ratio Shiny&amp;quot;
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    source_code: embed
---
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This app could have been built using an app.r file, but I prefer to use a flexdashboard because it keeps the entire workflow in the Rmarkdown world. In the previous post, we started with a Notebook (also an Rmarkdown file type) and made use of code chunks to enforce logic on our data import, calculations and visualizations. This Shiny app makes use of the same code chunk structure, and I find that the logic translates well. For example, the setup chunks are almost identical and contain our most important function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;```{r setup, message = FALSE}
library(shiny)
library(flexdashboard)
library(PerformanceAnalytics)
library(quantmod)
library(dygraphs)

# Function to calculate monthly returns on a stock
monthly_stock_returns &amp;lt;- function(ticker, start_year) {
  # Download the data from Yahoo finance
  symbol &amp;lt;- getSymbols(ticker, src = &#39;yahoo&#39;, from = start_year,
                       auto.assign = FALSE, warnings = FALSE)
  # Tranform it to monthly returns using the periodReturn function from quantmod
  data &amp;lt;- periodReturn(symbol, period = &#39;monthly&#39;, type = &#39;log&#39;)

  # Let&#39;s rename the column of returns to something intuitive because the column
  # name is what will eventually be displayed on the time series graph
  colnames(data) &amp;lt;- as.character(ticker)

  # We want to be able to work with the xts objects that result from this function
  # so let&#39;s explicitly put them to the global environment with an easy to use
  # name, the stock ticker
  assign(ticker, data, .GlobalEnv)
}
```
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The sidebar code chunk is, of course, unique to the Shiny app, because there are no reactive inputs in a Notebook. But the dygraphs code chunks are similar enough that it&amp;rsquo;s easy to transfer the Notebook code, with a few changes, over to the flexdashboard:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;```{r}
##dygraph chunk
dygraphOutput(&amp;quot;dygraphDollarGrowth&amp;quot;)

output$dygraphDollarGrowth%
    dyAxis(&amp;quot;y&amp;quot;, label = &amp;quot;$&amp;quot;) %&amp;gt;%
    dyOptions(axisLineWidth = 1.5, fillGraph = TRUE, drawGrid = TRUE)
})
```
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;File formats aside, from a team workflow perspective, this conversion to a Shiny app is super important - it&amp;rsquo;s where the R coders co-mingle with team members who need to make use of R&amp;rsquo;s analytical tools, but do not want to touch the code. For example, we can imagine a portfolio manager who wants the ability to quickly iterate through different portfolios and compare Sharpe Ratios, for internal construction purposes or perhaps even in a client-facing context. The PM does not want to write or reproduce this R code; he or she wants to focus on the portfolio.&lt;/p&gt;

&lt;p&gt;In other words, a PM wants to see this:&lt;/p&gt;

&lt;p&gt;&lt;img src=&#34;https://www.rstudio.com/wp-content/uploads/2016/11/finance_shiny_app.png&#34; alt=&#34;&#34; /&gt;&lt;/p&gt;

&lt;p&gt;Not this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;```{r}
##dygraph chunk
dygraphOutput(&amp;quot;dygraphDollarGrowth&amp;quot;)

output$dygraphDollarGrowth&amp;lt;-renderDygraph({
  dygraph(portfolio_growth(), main = &amp;quot;Growth of $1 Invested in Your Portfolio&amp;quot;) %&amp;gt;%
    dyAxis(&amp;quot;y&amp;quot;, label = &amp;quot;$&amp;quot;) %&amp;gt;%
    dyOptions(axisLineWidth = 1.5, fillGraph = TRUE, drawGrid = TRUE)
})
```

```{r}
valueBoxOutput(&amp;quot;approvalBox1&amp;quot;)
output$approvalBox1&amp;lt;-renderValueBox({
  valueBox(value = sharpe_ratio(), icon = &amp;quot;fa-line-chart&amp;quot;, color = &amp;quot;primary&amp;quot;)
})
```
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that the portfolio performance and Share Ratio calculations are consolidated and moved to the front page, and the individual stock returns are on the second page. The original Notebook had the opposite layout - we began with individual returns and progressed to the portfolio - because it was emphasizing the steps involved in arriving at the conclusion. We wanted our collaborators to start with the basics of grabbing stock return data and then proceed through each logical step.&lt;/p&gt;

&lt;p&gt;With this Shiny app, we don&amp;rsquo;t want to force our collaborators to go through our logic, because that is not the purpose of this app. End users of this app build and analyze portfolios, so let&amp;rsquo;s put those tools front and center. Give the users what they want!&lt;/p&gt;

&lt;p&gt;Have fun with this app, dream about buying tech stocks at their lows, and remember, as with our previous Notebook, that this app is a starting point. End users might want the ability to choose more than three stocks, or add bonds to the portfolio, or benchmark against a return other than a risk-free rate. This is where R coders and portfolio managers start to collaborate and build things bigger and better. Have a good weekend!&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2016/11/18/reproducible-finance-with-r-a-sharpe-ratio-shiny-app/&#39;;&lt;/script&gt;
      </description>
    </item>
    
  </channel>
</rss>
