Blogs home Featured Image

As we come to the end of Shiny Appreciation month we hope that the blog posts and tweets have encouraged more of you to start using Shiny to create your own interactive web applications.

If you need some help however with getting started with Shiny, or with more advanced functionality such as understanding reactivity, making plots interactive, debugging your app or writing reusable Shiny code, then the good news is that we have three new Shiny training courses.

These one-day courses run from getting started right through to best practices for putting Shiny into production environments.

The courses are being run publically in London in July and September:

  • Introduction to Shiny:    17th July
  • Intermediate Shiny:        18th July
  • Intermediate Shiny:        5th September
  • Advanced Shiny:              6th September

Alternatively, we can deliver the courses privately to individuals or groups if preferred. We will also be offering a snapshot of the materials for intermediate Shiny users at London EARL in September.

Importantly, all of these courses are taught by data science consultants who have hands-on experience building and deploying applications for commercial use. These consultants are supported by platform experts who can advise on the best approaches for getting an application out to end users so that you can see the benefits of using Shiny as quickly as possible.

For further details please take a look at our training page or contact us at


Blogs home Featured Image


What’s your background?

I’m a software engineer through and through. I majored in Management Science, but I’ve been working professionally as a programmer since my freshman year in college (1996, the start of the dot-com boom). I started out as a web developer and then, once I graduated and realized I wanted to spend my career writing software, focused on becoming a generalist software engineer. As a self-taught programmer, it took until about 2008 for my imposter syndrome to completely disappear.

I’ve spent most of my career at Boston-area startups, and I’ve enjoyed it tremendously. I’ve had the privilege of working with many wonderful people, and released a lot of software that I’m proud of (or at least, that I was proud of at the time!). In 2006, the startup I worked for was acquired by Microsoft, which meant a relocation to the Seattle area. In late 2009 I left Microsoft to join RStudio, but chose to remain in Seattle.

I’ve worked on a variety of software in my career: web, desktop, front end, back end. I take special pleasure in writing parsers and multithreaded code (generally not at the same time though!).

Tell us about your first experience with R

My very first experience with R was my first day at RStudio. JJ had been working on RStudio for a few months already, and the first feature he assigned to me was syntax highlighting of R code for the source editor. So before I ever wrote a line of R code, I was reading The R Language Definition and got intimately familiar with the grammar.

How did you come to work at RStudio?

JJ Allaire (RStudio’s founder) and I go back a ways. I was a web development intern at his first company, Allaire, which jump-started my software development career; and I also worked at his second startup, Onfolio. So I’ve basically been working for JJ on and off since 1997.

At the time that JJ was thinking about R, I was working at Microsoft, itching to get back into a startup. As soon as JJ convinced himself that a web-based IDE for R was technically feasible, he brought me in to help him build it, and I started in September 2009. Unlike JJ, I wasn’t interested in statistics at all. But the technical challenge of building a web-based IDE was alluring, and I was not going to turn down the chance to work with JJ directly.

In those days, it was not at all clear to us whether we could build a sustainable business writing tools for R users. Luckily, JJ didn’t care—he wanted to make the IDE a reality whether we ever saw a dollar or not, and he was willing to invest both his own time and my salary to make that happen. Obviously, the best case scenario was to build a robust business, so we could hire more people to write more good software.

What does your role as CTO at RStudio involve?

Actually, the majority of my job is working on Shiny and leading the Shiny team. Mostly what I do is try to move Shiny forward. I still code, but not nearly as much as I would like. On any given day, I might be writing docs, investigating trickier bugs, explaining parts of the code to other team members, reviewing PRs, prioritizing feature lists, planning releases, checking on peoples’ status, and reporting our team’s status to other people. I also speak at conferences a few times a year, and those presentations usually take me a really pathologically long time to prepare.

The title of CTO doesn’t define my responsibilities, but instead is more of an acknowledgement that as the longest tenured RStudio employee, and having been intimately involved in the creation of many of our products (RStudio IDE, Shiny, Shiny Server, and Connect), I should have a seat at the table when we make major company decisions. I do take part in a lot of technical discussions and decisions outside of my team, but the same could be said for a lot of other experienced technical folks around RStudio: JJ, Hadley, Jonathan McPherson, Aron Atkins, Tareef Kawaf, and on and on.

Going forward, I’m hoping to find a way to clear my schedule so I can get down to writing a book about Shiny. I’m astonished that people like Hadley, Garrett, and Yihui can write whole books while still doing their jobs; it takes all my concentration to write well and I find it extremely taxing, though ultimately satisfying.

Shiny Origins

What led you to create the Shiny framework?

From pretty early on, JJ and I received feedback from potential users that they wanted the ability to create interactive applets and reports using R. The first person who asked us for this was Danny Kaplan at Macalester College (who was also the first beta tester of RStudio). At the time, he was having grad students learn Java so they could build in-browser applets to help students explore statistical concepts. He implored us to make it possible to build those applets in R instead.

JJ and I both thought the idea was really appealing, but we were 100% focused on RStudio IDE at the time. I told JJ I thought we should do it someday, but only if we could come up with a really great API for doing so. Having spent years specializing in UI programming for both desktop and web, I really did not want to subject R users to that highly specialized black art.

The hard part of web UI programming, to me, was not HTML and JavaScript. Learning those just required time. Rather, it was the explosion of state management spaghetti code that inevitably occurred when creating even moderately complicated UIs, regardless of language. In my experience, it was possible to create complicated UIs without exponentially increasing code complexity, but it required experience, discipline, and a bit of luck. Only the very best teams could pull it off.

In April 2012, the Meteor JavaScript framework was announced on Hacker News. The Meteor screencast evoked for me the old Arthur C. Clarke quote, “Any sufficiently advanced technology is indistinguishable from magic.” Despite having just built a state of the art app in RStudio IDE, I could not conceive of how their framework’s UI layer could be so interactive with so little state management code. I couldn’t stop thinking about that mystery, so a couple of weeks later, I took advantage of a long plane flight to delve into the Meteor source code. I eventually ended up at this tiny JavaScript file, and the light bulb went on. It was an incredibly elegant little hack that enabled a whole new style of UI programming.

It took a few more months before I made the connection that Meteor-style reactivity could be used on the server side to create a high-level app framework for R.

How long did it take to come up with?

It took a couple of years between Danny asking us for a web framework, and the conception of Shiny, during which I spent zero time consciously thinking about it. But the Meteor reactivity implementation must have worked its way into my subconscious. On the last morning of useR! 2012, I woke up and literally the first thought in my mind was the architecture of Shiny: a simple, semantic HTML vocabulary for specifying inputs and outputs; a reactive programming library on the server side for specifying those outputs using pure R code; and some JavaScript and WebSocket plumbing to tie everything together automatically. JJ added the final piece, which was specifying the HTML itself using R.

Were there any unexpected challenges in that first version?

All of the ideas turned out to be really surprisingly easy to implement. Those first few months, JJ and I made progress at an almost absurd pace. During that period, I almost couldn’t type fast enough to get the ideas out of my head and into code. Reactive programming was this fantastically powerful and general technique, but once you knew about the little hack from deps.js, actually implementing it was dead simple.

Work on Shiny officially started on June 20, 2012. The first prototype of Shiny was actually written in Ruby (as I barely knew R at the time), just to prove the architecture. It took a day and a half to go from zero to a working little Shiny.rb app. (You can see the state of the repo on that day here. Looking at server.rb and www/index.html, you can clearly see that the core ideas in Shiny were present back then.)

The biggest challenge in those early days was the lack of a truly robust web server package for R. We needed not only a traditional HTTP server, but also support for WebSockets, which was not even an IETF-approved standard at that time. We started out building Shiny on top of the websockets package by Bryan Lewis, an early friend of the company. I’m not sure what had compelled Bryan to write the package in the first place, but by the time we adopted it, he had moved on and was looking to transfer the maintainership to someone else. I gratefully accepted the responsibility. But soon after we shipped the first versions of Shiny, it became clear to me that we couldn’t keep going with the websockets package, as it was trivially vulnerable to denial-of-service attacks and I couldn’t fix it without starting over from scratch. Shiny was already on CRAN and interest in it was growing quickly, so I felt tremendous pressure to get us onto a stable foundation. The result was a six week, hair-on-fire sprint to create httpuv, which I published to CRAN in March of 2013.

Besides that, the biggest challenges were API design and writing good docs. The former was especially challenging because I had so little R experience at the time, which made it hard to design APIs that would feel idiomatic to R users (to the degree that a reactive web framework could feel idiomatic!). So the addition of Hadley and Winston Chang to the company in late 2012 was a huge help, and led to significant changes in the API. Writing good docs, on the other hand, is just hard. It’s so much easier to build a web framework than to teach people how to use it effectively. We made a big push for that initial release, but it was years before the documentation even began to catch up to fully describe what we had built (and in some areas, still hasn’t).

Did the reception to Shiny surprise you?

It really did. I knew we had created something that was technically interesting, demoed especially well, and served a need that R users would find interesting. What I didn’t know was whether the community could get their heads around reactive programming, or rather, whether they’d be willing to invest the time necessary to get their heads around it. I was shocked to find how eager people were to jump in and invest. Within the first month we were already getting really surprisingly sophisticated questions from people we’d never met.

Have you been surprised by the ways in which it’s been used?

On one hand, yes, constantly. A lot of the features we’ve added over the years were inspired by brave users who managed to shoehorn Shiny into a scenario that we had not designed for. And every time I teach a training workshop, at least one person will ask me to look at some bug in their app that they haven’t been able to figure out, and then demo some mind-blowing thing.

But at another level, I’m not that surprised that people have built surprising things with Shiny, if that makes sense. Shiny provides a pretty general set of capabilities, in that it gives you a way to create user interfaces and a way to make them interactive. So there was always the expectation that if R users were sufficiently motivated and invested, they could build really cool things that we had never thought of–and that’s exactly what happened.

The present

Will async become the default for Shiny?

No, not a chance! I think of async as raising the ceiling on Shiny’s potential scalability, but most apps shouldn’t need to use it. But I hope most users will feel good knowing it’s there in case they ever do need it.

In terms of products, we see a lot of people using RStudio Connect, what’s going on with that right now?

For those who aren’t familiar, RStudio Connect is our answer to on-premises publishing and sharing of the reports and apps you create in R. First, you can use it to deploy Shiny apps to your on-prem server without leaving RStudio—it’s just like publishing to Second, it’s an extremely powerful R Markdown publishing server: you author .Rmd docs in RStudio as usual, but then you can one-click publish your project to Connect. Once on Connect, your report can be re-rendered on a schedule, run with user-specified parameters, automatically emailed to your colleagues, and more.

One of the recent focuses for the Connect team has been expanding the types of projects you can publish, beyond Shiny and R Markdown. The last release added support for deploying Plumber APIs (web service endpoints written in R) and TensorFlow deep learning models.

Another feature that’s under development is a programmatic API for the Connect server itself. This will let you programmatically execute tasks that previously needed to be performed through Connect’s user interface. This is an important feature for enterprises, who often want to integrate Connect to their existing systems.

There’s plenty more to come, but I’ve been sworn to secrecy!

At what point do you think it becomes useful for an R user to know some JavaScript when working with Shiny?

A lot of R users seem to come to JavaScript through d3, and that’s a totally understandable motivation. Personally, I think any R users who seriously want to get into bespoke visualization should consider JavaScript as their second programming language. That said, a lot of Shiny users have built pretty sophisticated apps without directly writing a line of JavaScript (the shinyjs package helps bridge the gap).

I would encourage R users who have JavaScript skills, to look for opportunities to package up JavaScript code into a friendly R package, so that R users who don’t (yet) know JavaScript can take full advantage of your work. The htmlwidgets package is the most popular way of doing this and is ideal for wrapping JS-based visualizations.

The future

How does the future look for Shiny? Can you share any of your plans?

We’ve just come off a big 18 months of work where we had a big focus on making Shiny easier to deploy in production settings: regression testing with shinytest, load testing with shinyloadtest, a new mechanism for scaling with async. In the near term, we’ll be following up with a new plot caching feature that can dramatically speed up certain classes of apps, and a ground-up rewrite of the reactivity visualizer that will finally deliver on the promise that the original implementation (?showReactLog) only hinted at.

We have some plans for the rest of the year, but we’re not ready to talk about them just yet, sorry!

Do you have an overall roadmap for Shiny and is there anything you can tell us about that?

We’ve always been much more reactive than proactive in our planning for Shiny. We almost didn’t have a choice about it in the early years, when every month we were learning so much about how people wanted to use Shiny and the problems they were encountering. That’s not to say that we don’t have a long backlog of features, fixes, documentation, and examples we’d love to tackle; just that we traditionally don’t commit to anything until we start working on it, in case it’s preempted by something we decide is more important.

I suspect we will need to adopt a formal roadmap someday soon. Both the Shiny team and RStudio as a company have grown so much that the lightweight processes I’ve insisted on in the past have started to break down.

And the one we all really want to know the answer to…

Why did you call it Shiny?

It’s from the late and lamented sci-fi series Firefly; in the show, they casually toss that word around to mean “cool”. I just liked the sound of it, and thought it’d make a good name for an open source library, but not for RStudio as we tended to use mostly straightforward, literal names in those days (“RStudio”, “R Markdown”, “RPubs”).

When the time came to create the GitHub repo for our new R web framework project, I intended it to call it something bland—not “RWeb”, but similar. But something strange happened. The new repo page on GitHub has a little prompt that suggests a random name for your repo, and to my delight, this time it said “Need inspiration? How about shiny-octocat.” I took that as a sign, named the repo Shiny, and despite some moments of doubt, it ultimately stuck.

Hmmm, I wonder if it’s too late to rename the shinytest package “gorram“.

Blogs home Featured Image

Becoming a data-driven business is high on the agenda of most companies but it can be difficult to know how to get started or know what the opportunities could be.

Mango Solutions’ has a bespoke workshop, ‘Art of The Possible’ to help senior leadership teams see the potential and overcome some of the common challenges.

Find out more in our new report developed in partnership with IBM.

Blogs home Featured Image

The challenge

Recently I saw that StackOverflow released their survey data and had been posted on Kaggle. The data came with the following context “Want to dive into the results yourself and see what you can learn about salaries or machine learning or diversity in tech?” and given that June is indeed shiny-appreciation month, I thought this would be a fun opportunity to combine an interesting public dataset, some exploratory analysis in shiny and uhhh.. my first blog.

Talking about this with a colleague at work, we both decided to independently have a crack and then compare our approaches. You can check out his blog here.

The data and idea

The data looked very rich, with almost 100k rows and 129 variables – a feast for any data addict. Feeling gluttonous, I wanted to take a bite out of every variable but without writing a tonne of code. So… iteration!

Exploration through iteration

Typically, the apps I have written in the past have consisted of a small number of well defined outputs in a fixed layout. Whilst this is appropriate for presenting a prescribed analysis, it is a bit cumbersome and slow for exploration. For this app, I wanted a different approach which had fast exploration, dynamic layout and hopefully powered by a small amount of code.

To do this, I would need a more programmatic way of creating UI elements and their corresponding outputs. The only non-reactive ui element that I needed is a simple selectInput (for the user to select variables), all other UI elements and outputs would then react to this selection. To allow for reactive ui elements I needed to stick in a ui placeholder uiOutput which would then be defined server-side with renderUI

ui <- fluidPage(
  # User selection
              label = "Select columns to visualise",
              choices = colnames(survey_data),
              multiple = TRUE,
              width = '800px'),
  # UI placeholder

Having finished the basic structure on the UI side, I made a start on a programmatic way of creating the ui outputs (in this case, using plotOutput). The basic idea here is to create an output placeholder for each selection the user makes. Each of these outputs will have an associated id of the selected variables. To make it work, we require returning a list of these outputs inside the renderUI expression – this can be achieved by using tagList (shiny equivalent of a list) and assigning elements iteratively using a for loop.

server <- function(input, output) {
  # Define our UI placeholder using the user selection
  output$p <- renderUI({
    # Define an empty tagList
    plots <- tagList()
    # Iterate over input column selection
    for (col in input$cols) {
      plots[[col]] <- plotOutput(col)

At this point, we have created a list of output placeholders but haven’t defined what these outputs will look like.

Before showing the code, I want to address some of the parts that need to come together to make this work. Firstly, we need our output to reactively render depending on the selection made by the user. In our case, we have a reactive input called input$cols. Now for each element of this input, we want to render a plot so the looping needs to be outside of the render statement (unlike the ui creation that looped inside a render statement) but as we are looping over a reactive object, we require a reactive context – in this case an observe statement fits perfectly.

server <- function(input, output) {
  # Define our UI placeholder using the user selection
  output$p <- renderUI({
    # Define an empty tagList (shiny equivalent of a list)
    plots <- tagList()
    # Iterate over input column selection
    for (col in input$cols) {
      plots[[col]] <- plotOutput(col)
  # Define created outputs
    # Iterate over input column selection
    lapply(input$cols, function(col) {
      # Render output for each associated output id
      output[[col]] <- renderPlot({
        hist(rnorm(10), main = col)

Back to the StackOverflow survey

In the previous sections, I introduced how to construct ui and server creation by way of iteration. Now I want to combine it with the StackOverflow survey to show how this kind of app can be effective for quick exploratory analysis.

There are many ways that we can explore a dataset but I have gone for pure simplicity – plotting a univariate distribution for each variable (histogram for continuous, barplot for categorical). The only other notable shiny addition is the use of validateto firstly have some control over which variables are plotted but also to give the user an informative message of why a plot isn’t shown.

You can test out the app (with a sample of the total data) here or the full code can be found below:

# Packages

# Data (change to appropriate file path)
survey_data <- read_csv("../data/survey_results_public.csv")

# Defining the UI part of the app
ui <- fluidPage(
    width = 6,
    offset = 3,
                  label = "Select columns to visualise",
                  choices = colnames(survey_data),
                  multiple = TRUE,
                  width = '800px')
  # Main output
    width = 8,
    align = "center",
    offset = 2,

# Defining the server part of the app
server <- function(input, output) {
  # Define our UI placeholder using the user selection
  output$p <- renderUI({
    # Define an empty tagList (shiny equivalent of a list)
    plots <- tagList()
    # Iterate over input column selection
    for (col in input$cols) {
      plots[[col]] <- plotOutput(col)
  # Trigger everytime the input columns are changed
    lapply(input$cols, function(col) {
      # Remove NA entries
      d <- survey_data[![[col]]), ]
      # Column class
      cc <- class(d[[col]])
      output[[col]] <- renderPlot({
        # Plots only defined for chracter, numeric & integer
        validate(need(cc %in% c("character", "numeric", "integer"),
                      paste("Plots undefined for class", cc)))
        if (cc == "character") {
          # Only show barplot if we have fewer than 20 bars
          validate(need(length(unique(d[[col]])) < 20,
                        paste(col, "contains more than 20 levels")))
          # Basic ggplot barplot
          ggplot(d, aes_string(x = col)) +
            geom_bar() +
            coord_flip() +
            theme_bw() +
        } else {
          # Basic ggplot histogram
          ggplot(d, aes_string(x = col)) +
            geom_histogram() +
            theme_bw() +

shinyApp(ui = ui, server = server)


For me, Shiny’s great strength is it’s versatility; analysis can come in many shapes and sizes so it is only fitting that Shiny, a framework for sharing analysis, can also be written in multitude of ways. In this blog post, the app wasn’t particularly snazzy (so probs not to be shared with the senior managers or as an ‘inspirational’ linkedin post) but it does what I want: quick exploration, dynamic layout & less than 100 lines of code!

My colleague Graham opted for a totally different app, one which presented the user with a well thought out and defined model. Again demonstrating the many use cases Shiny can have in a project. Not only can it be used at the start as an exploratory tool but also at the end to present findings, predictions and other project outcomes.

Asides from that, I had a lot of fun exploring the survey data, especially variables relating to health-lifestyle of developers – I’m no physician but, devs, try to do at least some exercise… Wishing you all a happy end to shiny-appreciation month, keep writing ’em apps, and see ya next time 🙂

Blogs home

James Blair, RStudio

Scalability is a hot word these days, and for good reason. As data continues to grow in volume and importance, the ability to reliably access and reason about that data increases in importance. Enterprises expect data analysis and reporting solutions that are robust and allow several hundred, even thousands, of concurrent users while offering up-to-date security options.

Shiny is a highly flexible and widely used framework for creating web applications using R. It enables data scientists and analysts to create dynamic content that provides straightforward access to their work for those with no working knowledge of R. While Shiny has been around for quite some time, recent introductions to the Shiny ecosystem make Shiny simpler and safer to deploy in an enterprise environment where security and scalability are paramount. These new tools in connection with RStudio Connect provide enterprise grade solutions that make Shiny an even more attractive option for data resource creation.

Develop and Test

Most Shiny applications are developed either locally on a personal computer or using an instance of RStudio Server. During development it can be helpful to understand application performance, specifically if there are any concerning bottlenecks. The profvis package provides functions for profiling R code and can profile the performance of Shiny applications. profvis provides a breakdown of code performance and can be useful for identifying potential areas for improving application responsiveness.

The recently released promises package provides asynchronous capabilities to Shiny applications. Asynchronous programming can be used to improve application responsiveness when several concurrent users are accessing the same application. While there is some overhead involved in creating asynchronous applications, this method can improve application responsiveness.

Once an application is fully developed and ready to be deployed, it’s useful to establish a set of behavioral expectations. These expectations can be used to ensure that future updates to the application don’t break or unexpectedly change behavior. Traditionally most testing of Shiny applications has been done by hand, which is both time consuming and error prone. The new shinytest package provides a clean interface for testing Shiny applications. Once an application is fully developed, a set of tests can be recorded and stored to compare against future application versions. These tests can be run programatically and can even be used with continuous integration (CI) platforms. Robust testing for Shiny applications is a huge step forward in increasing the deployability and dependability of such applications.


Once an application has been developed and tested to satisfaction, it must be deployed to a production environment in order to provide other users with application access. Production deployment of data resources within an enterprise centers on control. For example, access control and user authentication are important for controlling who has access to the application. Server resource control and monitoring are important for controlling application performance and server stability. These control points enable trustworthy and performant deployment.

There are a few current solutions for deploying Shiny applications. Shiny Server provides both an open source and professional framework for publishing Shiny applications and making them available to a wide audience. The professional version provides features that are attractive for enterprise deployment, such as user authentication. RStudio Connect is a recent product from RStudio that provides several enhancements to Shiny Server. Specifically, RStudio Connect supports push button deployment and natively handles application dependencies, both of which simplify the deployment process. RStudio Connect also places resource control in the hands of the application developer, which lightens the load on system administrators and allows the developer to tune app performance to align with expectations and company priorities.


In order to be properly leveraged, a deployed application must scale to meet user demand. In some instances, applications will have low concurrent users and will not need any additional help to remain responsive. However, it is often the case in large enterprises that applications are widely distributed and concurrently accessed by several hundred or even thousands of users. RStudio Connect provides the ability to set up a cluster of servers to provide high availability (HA) and load balanced configurations in order to scale applications to meet the needs of concurrent users. Shiny itself has been shown to effectively scale to meet the demands of 10,000 concurrent users!

As businesses continue searching for ways to efficiently capture and digest growing stores of data, R in connection with Shiny continues to establish itself as a robust and enterprise ready solution for data analysis and reporting.

Blogs home

There are times when it costs more than it should to leverage javascript, database, html, models and algorithms in one language. Now maybe is time for connecting some dots, without stretching too much.

  • If you have been developing shiny apps, consider letting it sit on one live database instead of manipulating data I/O by hand?
  • If you use DT to display tables in shiny apps, care to unleash the power of interactivity to its full?
  • If you struggle with constructing SQL queries in R, so did we.

Inspired (mainly) by the exciting new inline editing feature of DT, we created a minimal shiny app demo to show how you can update multiple values from DT and send the edits to database at a time.

As seen in the screenshot, after double clicking on a cell and editing the value, Save and Cancel buttons will show up. Continue editing, the updates are stored in a temporary (reactiveValue) object. Click on Save if you want to send bulk updates to database; click on Cancel to reset.


On the global level, we use pool to manage database connections. A database connection pool object is constructed. With the onStop() function, the pool object gets closed after a session ends. It massively saves you from worrying about when to open or close a connection.

# Define pool handler by pool on global level
pool <- pool::dbPool(drv = dbDriver("PostgreSQL"),
                     user= "postgres",

onStop(function() {
}) # important!

The next job is to define a function to update database. The glue_sql function puts together a SQL query in a human readable way. Writing SQL queries in R was bit of a nightmare. If you used to assemble a SQL clause by sprintf or past, you know what I’m talking about. The glued query is then processed by sqlInterpolate for SQL injection protection before being executed.

updateDB <- function(editedValue, pool, tbl){
  # Keep only the last modification for a cell
  editedValue <- editedValue %>% 
    group_by(row, col) %>% 
    filter(value == dplyr::last(value)| %>% 

  conn <- poolCheckout(pool)

  lapply(seq_len(nrow(editedValue)), function(i){
    id = editedValue$row[i]
    col = dbListFields(pool, tbl)[editedValue$col[i]]
    value = editedValue$value[i]

    query <- glue::glue_sql("UPDATE {`tbl`} SET
                          {`col`} = {value}
                          WHERE id = {id}
                          ", .con = conn)

    dbExecute(conn, sqlInterpolate(ANSI(), query))



We begin with server.R from defining a couple of reactive values: data for most dynamic data object, dbdata for what’s in database, dataSame for whether data has changed from database, editedInfo for edited cell information (row, col and value). Next, create a reactive expression of source data to retrieve data, and assign it to reactive values.

# Generate reactive values
rvs <- reactiveValues(
  data = NA, 
  dbdata = NA, 
  dataSame = TRUE, 
  editedInfo = NA 

# Generate source via reactive expression
mysource <- reactive({
  pool %>% tbl("nasa") %>% collect()

# Observe the source, update reactive values accordingly
observeEvent(mysource(), {

  # Lightly format data by arranging id
  # Not sure why disordered after sending UPDATE query in db    
  data <- mysource() %>% arrange(id)

  rvs$data <- data
  rvs$dbdata <- data


We then render a DataTable object, create its proxy. Note that the editable parameter needs to be explicitly turned on. Finally with some format tweaking, we can merge the cell information, including row id, column id and value, with DT proxy and keep all edits as a single reactive value. See examples for details.

# Render DT table and edit cell
# no curly bracket inside renderDataTable
# selection better be none
# editable must be TRUE
output$mydt <- DT::renderDataTable(
  rvs$data, rownames = FALSE, editable = TRUE, selection = 'none'

proxy3 = dataTableProxy('mydt')

observeEvent(input$mydt_cell_edit, {

  info = input$mydt_cell_edit

  i = info$row
  j = info$col = info$col + 1  # column index offset by 1
  v = info$value

  info$value <- as.numeric(info$value)

  rvs$data[i, j] <<- DT::coerceValue(v, purrr::flatten_dbl(rvs$data[i, j]))
  replaceData(proxy3, rvs$data, resetPaging = FALSE, rownames = FALSE)

  rvs$dataSame <- identical(rvs$data, rvs$dbdata)

  if (all($editedInfo))) {
    rvs$editedInfo <- data.frame(info)
  } else {
    rvs$editedInfo <- dplyr::bind_rows(rvs$editedInfo, data.frame(info))

Once Save button is clicked upon, send bulk updates to database using the function we defined above. Discard current edits and revert DT to last saved status of database when you hit Cancel. Last chunk is a little trick that generates interactive UI buttons. When dynamic data object differs from the database representative object, show Save and Cancel buttons; otherwise hide them.

# Update edited values in db once save is clicked
observeEvent(input$save, {
  updateDB(editedValue = rvs$editedInfo, pool = pool, tbl = "nasa")

  rvs$dbdata <- rvs$data
  rvs$dataSame <- TRUE

# Observe cancel -> revert to last saved version
observeEvent(input$cancel, {
  rvs$data <- rvs$dbdata
  rvs$dataSame <- TRUE

# UI buttons
output$buttons <- renderUI({
    if (! rvs$dataSame) {
        actionButton(inputId = "save", label = "Save",
                     class = "btn-primary"),
        actionButton(inputId = "cancel", label = "Cancel")
    } else {


The UI part is exactly what you normally do. Nothing new.

Bon Appétit

  1. Set up a database instance e.g. PostgreSQL, SQLite, mySQL or MS SQL Server etc.
  2. Download/clone the GitHub repository
  3. Run through script app/prep.R but change database details to one’s own. It writes to DB our demo dataset which is the nasa dataset from dplyr with an index column added
  4. Also update database details in app/app.R and run

Workhorse functionality is made possible by:

  • DBI: R Database Interface
  • RPostgreSQL: R Interface to PostgreSQL (one of many relational database options)
  • pool: DBI connection object pooling
  • DT: R Interface to the jQuery Plug-in DataTables (requires version >= 0.2.30)
  • Shiny: Web Application Framework for R
  • dplyr: Data manipulation
  • glue: Glue strings to data in R. Small, fast, dependency free interpreted string literals (requires version >= Blank cell crashes the app with version 1.2.0)

Learn how to use Shiny with our Introduction, Intermediate and Advanced courses.

FIFA World Cup 2018 predictions
Blogs home Featured Image

Given that the UEFA Champion League final a few weeks ago between Real Madrid and Liverpool is the only match I’ve watched properly in over ten years, how dare I presume I can guess that Brazil is going to lift the trophy in the 2018 FIFA World Cup? Well, here goes…

By the way, if you find the below dry to read, it is because of my limited natural language on the subject matter…data science tricks to the rescue!

The idea is that in each simulation run of a tournament, we find team winner, runners-up, third and fourth etc. N times of simulation runs e.g. 10k returns a list of winners with highest probability to be ranked top.


normalgoals <- params$normalgoals 
nsim <- params$nsim


Apart from the winner question, this post seeks to answer which team will be top scorer and how many goals will they score. After following Claus’s analysis rmarkdown file, I collected new data, put functions in a package and tried another modelling approach. Whilst the model is too simplistic to be correct, it captures the trend and is a fair starting point to add complex layers on top.


To begin with, we load packages including accompanying R package worldcup where my utility functions reside. Package is a convenient way to share code, seal utility functions and speed up iteration. Global parameters normalgoals (the average number of goals scored in a world cup match) and nsim (number of simulations) are declared in the YAML section at the top of the RMarkdown document.

Next we load three datasets that have been tidied up from open source resource or updated from original version. Plenty of time was spent on gathering data, aligning team names and cleaning up features.

  • team_data contains features associated with team
  • group_match_data is match schedule, public
  • wcmatches_train is a match dataset available on this Kaggle competition and can be used as training set to estimate parameter lamda i.e. the average goals scored in a match for a single team. Records from 1994 up to 2014 are kept in the training set.

Play game

Claus proposed three working models to calculate single match outcome. The first is based on two independent poisson distributions, where two teams are treated equal and so the result is random regardless of their actual skills and talent. The second assumes the scoring event in a match are two possion events, the difference of two poisson events believed to have skellam distribution. The result turns out to be much more reliable as the parameters are estimated from actual bettings. The third one is based on World Football ELO Ratings rules. From current ELO ratings, we calculate expected result of one side in a match. It can be seen as the probability of success in a binomial distribution. It seems that this approach overlooked draw due to the nature of binomial distribution i.e. binary.

The fourth model presented here is my first attempt. To spell out: we assumed two independent poisson events, with lambdas predicted from a trained poisson model. Then predicted goal is simulated by rpois.

Model candidate each has its own function, and it is specified by the play_fun parameter and provided to higher level wrapper function play_game.

# Specify team Spain and Portugal
play_game(play_fun = "play_fun_simplest", 
          team1 = 7, team2 = 8, 
          musthavewinner=FALSE, normalgoals = normalgoals)
##      Agoals Bgoals
## [1,]      0      1
play_game(team_data = team_data, play_fun = "play_fun_skellam", 
          team1 = 7, team2 = 8, 
          musthavewinner=FALSE, normalgoals = normalgoals)
##      Agoals Bgoals
## [1,]      1      4
play_game(team_data = team_data, play_fun = "play_fun_elo", 
          team1 = 7, team2 = 8)
##      Agoals Bgoals
## [1,]      0      1
play_game(team_data = team_data, train_data = wcmatches_train, 
          play_fun = "play_fun_double_poisson", 
          team1 = 7, team2 = 8)
##      Agoals Bgoals
## [1,]      2      2

Estimate poisson mean from training

Let’s have a quick look at the core of my training function. Target variable in the glm function is the number of goals a team obtained in a match. Predictors are FIFA and ELO ratings at a point before the 2014 tournament started. Both are popular ranking systems – the difference being that the FIFA rating is official and the latter is in the wild, adapted from chess ranking methodology.

mod <- glm(goals ~ elo + fifa_start, family = poisson(link = log), data = wcmatches_train)
##          term      estimate    std.error  statistic      p.value
## 1 (Intercept) -3.5673415298 0.7934373236 -4.4960596 6.922433e-06
## 2         elo  0.0021479463 0.0005609247  3.8292949 1.285109e-04
## 3  fifa_start -0.0002296051 0.0003288228 -0.6982638 4.850123e-01

From the model summary, the ELO rating is statistically significant whereas the FIFA rating is not. More interesting is that the estimate for the FIFA ratings variable is negative, inferring the effect is 0.9997704 relative to average. Overall, FIFA rating appears to be less predictive to the goals one may score than ELO rating. One possible reason is that ratings in 2014 alone are collected, and it may be worth future effort to go into history. Challenge to FIFA ratings’ predictive power is not new after all.

Training set wcmatches_train has a home column, representing whether team X in match Y is the home team. However, it’s hard to say in a third country whether a team/away position makes much difference comparing to league competetions. Also, I didn’t find an explicit home/away split for the Russian World Cup. We could derive a similar feature – host advantage, indicating host nation or continent in future model interation. Home advantage stands no better chance for the time being.

Group and kickout stages

Presented below are examples showing how to find winners at various stages – from group to round 16, quarter-finals, semi-finals and final.

find_group_winners(team_data = team_data, 
                   group_match_data = group_match_data, 
                   play_fun = "play_fun_double_poisson",
                   train_data = wcmatches_train)$goals %>% 
  filter(groupRank %in% c(1,2)) %>% collect()
## Warning: package 'bindrcpp' was built under R version 3.4.4

## # A tibble: 16 x 11
##    number name         group  rating   elo fifa_start points goalsFore
##  1      2 Russia       A       41.0   1685        493   7.00         5
##  2      3 Saudi Arabia A     1001     1582        462   5.00         4
##  3      7 Portugal     B       26.0   1975       1306   7.00         6
##  4      6 Morocco      B      501     1711        681   4.00         2
##  5     12 Peru         C      201     1906       1106   5.00         3
##  6     11 France       C        7.50  1984       1166   5.00         6
##  7     13 Argentina    D       10.0   1985       1254   9.00         8
##  8     15 Iceland      D      201     1787        930   6.00         4
##  9     17 Brazil       E        5.00  2131       1384   7.00         8
## 10     20 Serbia       E      201     1770        732   6.00         4
## 11     21 Germany      F        5.50  2092       1544   6.00         8
## 12     24 Sweden       F      151     1796        889   6.00         5
## 13     27 Panama       G     1001     1669        574   5.00         3
## 14     25 Belgium      G       12.0   1931       1346   5.00         4
## 15     31 Poland       H       51.0   1831       1128   4.00         2
## 16     29 Colombia     H       41.0   1935        989   4.00         1
## # ... with 3 more variables: goalsAgainst , goalsDifference ,
## #   groupRank 
find_knockout_winners(team_data = team_data, 
                      match_data = structure(c(3L, 8L, 10L, 13L), .Dim = c(2L, 2L)), 
                      play_fun = "play_fun_double_poisson",
                      train_data = wcmatches_train)$goals
##   team1 team2 goals1 goals2
## 1     3    10      2      2
## 2     8    13      1      2

Run the tournament

Here comes to the most exciting part. We made a function–simulate_one()–to play the tournament one time and then replicate() (literally) it many many times. To run an ideal number of simulations, for example 10k, you might want to turn on parallel. I am staying at 1000 for simplicity.

Finally, simulate_tournament() is an ultimate wrapper for all the above bullet points. The returned resultX object is a 32 by R params$nsim matrix, each row representing predicted rankings per simulation. set.seed() is here to ensure the result of this blogpost is reproducible.

# Run nsim number of times world cup tournament
result <- simulate_tournament(nsim = nsim, play_fun = "play_fun_simplest") 
result2 <- simulate_tournament(nsim = nsim, play_fun = "play_fun_skellam")
result3 <- simulate_tournament(nsim = nsim, play_fun = "play_fun_elo")
result4 <- simulate_tournament(nsim = nsim, play_fun = "play_fun_double_poisson", train_data = wcmatches_train)

Get winner list

get_winner() reports a winner list showing who has highest probability. Apart from the random poisson model, Brazil is clearly the winner in three other models. The top two teams are between Brazil and Germany. With different seeds, the third and fourth places (in darker blue) in my model are more likely to change. Variance might be an interesting point to look at.

get_winner(result) %>% plot_winner()

get_winner(result2) %>% plot_winner()

get_winner(result3) %>% plot_winner()

get_winner(result4) %>% plot_winner()

Who will be top scoring team?

The skellum model seems more reliable, my double poisson model gives systematically lower scoring frequency than probable actuals. They both favour Brazil though.

get_top_scorer(nsim = nsim, result_data = result2) %>% plot_top_scorer()

get_top_scorer(nsim = nsim, result_data = result4) %>% plot_top_scorer()


The framework is pretty clear, all you need is to customise the play_game function, such as game_fun_simplestgame_fun_skellam and game_fun_elo.

Tick-tock… Don’t hesitate to send a pull request to ekstroem/socceR2018 on GitHub. Who is winning the guess-who-wins-worldcup2018 game?

If you like this post, please leave your star, fork, issue or banana on the GitHub repository of the post, including all code ( The analysis couldn’t have been done without help from Rich, Doug, Adnan and all others who have kindly shared ideas. I have passed on your knowledge to the algorithm.


  1. Data collection. I didn’t get to feed the models with the most updated betting odds and ELO ratings in the team_data dataset. If you would like to, they are available via the below three sources. FIFA rating is the easiest and can be scraped by rvest in the usual way. The ELO ratings and betting odds tables seem to have been rendered by javascript and I haven’t found a working solution. For betting information, Betfair, an online betting exchange has an API and R package abettor which helps to pull those odds which are definetly interesting for anyone who are after strategy beyond prediction:
      1. Model enhancement. This is probably where it matters most. For example, previous research has suggested various bivariate poissons for football predictions.
      2. Feature engineering. Economic factors such as national GDP, market information like total player value or insurance value, and player injure data may be useful to improve accuracy.
      3. Model evaluation. One way to understand if our model has good prediction capibility or not is to evaluate the predictions against actual outcomes after 15 July 2018. Current odds from bookies can also be referred to. It is not imporssible to run the whole thing on historical data e.g. Year 2014. and perform model selection and tuning.
      4. Functions and package could be better parameterized; code to be tidied up.

Author: Ava Yang, Data Scientist at Mango Solutions

Blogs home Featured Image

If you use RStudio Connect to publish your Shiny app (and even if you don’t) take care with how your arrange your projects. If you have a single project that includes both your data prep and your Shiny app, packrat (which RSConnect uses to resolve package dependencies for your project) will assume the packages you used for both parts are required on the RSConnect server and will try to install them all.

This means that if your Shiny app uses three packages and your data prep uses six, packrat and RSconnect will attempt to install all nine on the server. This can be time consuming as packages are often built from source in Connect-based environments, so this will increase the deployment time considerably. Furthermore, some packages may require your server admin to resolve system-level package dependency issues, which may even be for packages that your app doesn’t use while it’s running.

Keeping data prep and your app within a single project can also confuse people who come on to your project as collaborators later in the development process, since the scope of the project will be less clear. Plus, documenting the pieces separately also helps to improve clarity.

Lastly, separating the two will make your life easier if you ever get to the stage where you want to start automating parts of your workflow as the data prep stage will already be separate from the rest of the project.

Clear separation of individual projects (and by extension, source code repositories) may cause some short term pain, but the long term benefits are hard to understate:

  • Smoother and faster RStudio Connect deployments
  • Easier collaboration
  • More straightforward automation (easier to build out into a pipeline)
  • Simpler to document – one set for the app, another for your data prep

Of course, if your Shiny app actually does data prep as part of the apps internal processing, then all bets are off!

Blogs home

For the last week we’ve been talking on the blog and Twitter about some of the functionality in Shiny and how you can learn it. But, if you haven’t already made the leap and started using Shiny, why should you?

What is the challenge to be solved?

At Mango we define data science as the proactive use of data and advanced analytics to drive better decision making.

We all know about the power of R for solving analytic challenges. It is, without a doubt, one of the most powerful analytic tools available to us as data scientists, providing the ability to solve modelling challenges using a range of traditional and modern analytic approaches.

However, the reality is that we can fit the best models and write the best code, but unless someone in the business is able to use the insight we generate to make a better decision our teams won’t add any value.

So, how do we solve this? How can we share the insight with the decision makers? How can we actually drive decision making with the analytics we have performed? If we’re not putting the results of our analysis into the hands of the decision makers it’s completely useless.

This is where Shiny comes in!

What is Shiny?

Shiny is a web application framework for R. In a nutshell this means that anyone who knows some R can start to build applications that sit in a web browser. It could be as simple as displaying some graphics and tables, to a fully interactive dashboard. The important part is that it is all done with R; there are no requirements for web developers to get involved.

Also, Shiny allows us to create true ‘data products’ that go beyond standard Business Intelligence dashboards. We can define intuitive interfaces that allow business users to perform what-if analysis, manipulating parameters that enable them to see the impact of different approaches on business outcomes.

What can it do?

Once your Shiny app is built it’s basically an interface to R – meaning your Shiny application can do whatever R can do (if you allow it to). So you can create Shiny applications that do anything from ‘add some numbers together’ to ‘fit sophisticated models across large data sources and simulate a variety of outputs’.

There are more use cases for Shiny than we could possibly list here and I would strongly recommend checking out the Shiny user showcase for more examples.

Share Insights

When it comes to Shiny for sharing insights some of the most common uses that we see include:

  • Presenting results of analysis to end users in the form of graphics and tables, allowing limited interaction such as selecting sub-groups of the data
  • Displaying current status and presenting recommended next actions based on R models
  • Automated production of common reports, letting users upload their own data that can be viewed in a standard way

Day-to-Day Data Tasks

Sharing insights is by no means the only way in which Shiny can be used. At Mango we are regularly asked by our customers to provide applications that allow non-R users to perform standard data manipulation and visualisation tasks or run standard analysis based on supplied data or data extracted from a database. Essentially, this allows the day to day tasks to move away from the data scientists or core R users who can then focus on new business challenges.

Check out this case study for an example of how we helped Pfizer with an application to simplify their data processing.


Shiny is also a great tool for prototyping. Whilst it can be, and is, used widely in production environments, some businesses may prefer to use other tools for business critical applications.

But allowing the data scientists in the team to generate prototypes in Shiny makes it much easier to understand if investment in the full system will add value, whilst also providing an interim solution.

The possibilities really are endless – in fact a question you may need to consider is: when should we move from Shiny to a formal web development framework?

But the decision makers don’t use R

The best thing about Shiny is that it produces a web application that can be deployed centrally and shared as a URL, just like any other web page. There are a whole host of tools that allow you to do this easily.

My personal favourite is RStudio Connect, as I can deploy a new application quickly and easily without having to spend time negotiating with the IT team. But there are other options and I would recommend checking out the RStudio website for a great resource comparing some of the most popular ones.

How can we get started with shiny?

There are a number of ways that you can get started understanding whether Shiny could add value in your business: from Shiny training courses to developing a prototype.

Get in touch with the team at Mango who will be happy to talk through your current business requirements and advise on the next best steps for putting the power of Shiny into your decision making process.

Why do we love Shiny?

Shiny allows R users to put data insights into the hands of the decision makers. It’s a really simple framework that doesn’t require any additional toolsets and allows all of the advanced analytics of R to be made available to the people who will be making the decisions.

Shiny Training at Mango

This month we have launched our newly updated Shiny training programme. The three one-day courses go from getting started right through to best practices for putting Shiny into production environments.

Importantly, all of these courses are taught by data science consultants who have hands-on experience building and deploying applications for commercial use. These consultants are supported by platform experts who can advise on the best approaches for getting an application out to end users so that you can see the benefits of using Shiny as quickly as possible.

If you want to know more about the Shiny training that we offer, take a look at our training page. If you are based in the UK we will be running public Shiny courses in London (see below for the currently scheduled dates). We will also be offering a snapshot of the materials for intermediate Shiny users at London EARL in September.

Public course dates:
  • Introduction to Shiny: 17th July
  • Intermediate Shiny: 18th July, 5th September
  • Advanced Shiny: 6th September

If you would like more information or to register for our Shiny courses, please contact our Training Team.