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 training@mango-solutions.com

 

Blogs home Featured Image

Background

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 ShinyApps.io. 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

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.

Deploy

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.

Scale

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.

Global

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"),
                     dbname="demo",
                     host="localhost",
                     user= "postgres",
                     password="ava2post")

onStop(function() {
  poolClose(pool)
}) # 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)| is.na(value)) %>% 
    ungroup()

  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))
  })

  poolReturn(conn)
  print(editedValue)  
  return(invisible())
}

Server

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(is.na(rvs$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({
  div(
    if (! rvs$dataSame) {
      span(
        actionButton(inputId = "save", label = "Save",
                     class = "btn-primary"),
        actionButton(inputId = "cancel", label = "Cancel")
      )
    } else {
      span()
    }
  )
})

UI

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
    shiny::runApp("app")
Acknowledgements

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 >= 1.2.0.9000. Blank cell crashes the app with version 1.2.0)

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

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.

Prototyping

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.

Blogs home

Back in the summer of 2012 I was meant to be focusing on one thing: finishing my thesis. But, unfortunately for me, a friend and former colleague came back from a conference (JSM) and told me all about a new package that she had seen demoed.

“You should sign up for the beta testing and try it out,” she said.

So, I did.

That package was Shiny and after just a couple of hours of playing around I was hooked. I was desperate to find a way to incorporate it into my thesis, but never managed to; largely due to the fact it wasn’t available on CRAN until a few months after I had submitted and because, at the time, it was quite limited in its functionality. However, I could see the potential – I was really excited about the ways it could be used to make analytics more accessible to non-technical audiences. After joining Mango I quickly became a Shiny advocate, telling everyone who would listen about how great it was.

Six years on at Mango, not a moment goes by when somebody in the team isn’t using Shiny for something. From prototyping to large scale deployments, we live and breathe Shiny. And we are extremely grateful to the team at RStudio—led by Joe Cheng—for the continued effort that they are putting in to its development. It really is a hugely different tool to the package I beta tested so long ago.

As Shiny has developed and the community around it has become greater so too has the need to teach it because more people than ever are looking to become Shiny users. For a number of years, we have been teaching the basics of Shiny to those who want to get started, and more serious development tools to those who want to deploy apps in production. But increasingly, we have seen a demand for more. And as the Shiny team have added more and more functionality it was time for a major update to our teaching materials.

Over the past six months we have had many long discussions over what functionality should be included. We have debated best practices, we have drawn on all of our combined experiences of both learning and deploying Shiny, and we eventually reached a consensus over what we felt was best for industry users of Shiny to learn.

We are now really pleased to announce an all new set of Shiny training courses.

Our courses cover everything from taking your first steps in building a Shiny application, to building production-ready applications and a whole host of topics in between. For those who want to take a private course we can tailor to your needs, and topics as diverse as getting the most from tables in DT to managing database access in apps can all be covered in just a few days.

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

But, one blog post was never going to be enough for all of the Shiny enthusiasts at Mango to share their passion. We needed more time, more than one blog post and more ways to share with the community.

Therefore, Mango are declaring June to be Shiny Appreciation Month!

For the whole of June, we will be talking all things Shiny. Follow us on Twitter where we will be sharing tips, ideas and resources. To get involved, share your own with us and the Shiny community, using #ShinyAppreciation. On the blog we will be sharing, among other things, some of the ways we are using Shiny in industry and some of the technical challenges we have had to overcome.

Watch this space for updates but, for now, if you want to know more about the Shiny training that we offer, take a look at our training pages. 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.

Blogs home

(Or, how to write a Shiny app.R file that only contains a single line of code)

This post is long overdue. The information contained herein has been built up over years of deploying and hosting Shiny apps, particularly in production environments, and mainly where those Shiny apps are very large and contain a lot of code.

Last year, during some of my conference talks, I told the story of Mango’s early adoption of Shiny and how it wasn’t always an easy path to production for us. In this post I’d like to fill in some of the technical background and provide some information about Shiny app publishing and packaging that is hopefully useful to a wider audience.

I’ve figured out some of this for myself, but the most pivotal piece of information came from Shiny creator, Joe Cheng. Joe told me some time ago, that all you really need in an app.R file is a function that returns a Shiny application object. When he told me this, I was heavily embedded in the publication side and I didn’t immediately understand the implications.

Over time though I came to understand the power and flexibility that this model provides and, to a large extent, that’s what this post is about.

What is Shiny?

Hopefully if you’re reading this you already know, but Shiny is a web application framework for R. It allows R users to develop powerful web applications entirely in R without having to understand HTML, CSS and JavaScript. It also allows us to embed the statistical power of R directly into those web applications.

Shiny apps generally consist of either a ui.R and a server.R (containing user interface and server-side logic respectively) or a single app.R which contains both. Why package a Shiny app anyway?

If your app is small enough to fit comfortably in a single file, then packaging your application is unlikely to be worth it. As with any R script though, when it gets too large to be comfortably worked with as a single file, it can be useful to break it up into discrete components.

Publishing a packaged app will be more difficult, but to some extent that will depend on the infrastructure you have available to you.

Pros of packaging

Packaging is one of the many great features of the R language. Packages are fairly straightforward, quick to create and you can build them with a host of useful features like built-in documentation and unit tests.

They also integrate really nicely into Continuous Integration (CI) pipelines and are supported by tools like Travis. You can also get test coverage reports using things like codecov.io.

They’re also really easy to share. Even if you don’t publish your package to CRAN, you can still share it on GitHub and have people install it with devtools, or build the package and share that around, or publish the package on a CRAN-like system within your organisation’s firewall.

Cons of packaging

Before you get all excited and start to package your Shiny applications, you should be aware that — depending on your publishing environment — packaging a Shiny application may make it difficult or even impossible to publish to a system like Shiny Server or RStudio Connect, without first unpacking it again.

* Since time of writing this information is now incorrect. Check out https://thinkr-open.github.io/golem/articles/c_deploy.html for more information on deploying packaged shinyapps to shiny server, shinyapps.io and rsconnect.

A little bit of Mango history

This is where Mango were in the early days of our Shiny use. We had a significant disconnect between our data scientists writing the Shiny apps and the IT team tasked with supporting the infrastructure they used. This was before we’d committed to having an engineering team that could sit in the middle and provide a bridge between the two.

When our data scientists would write apps that got a little large or that they wanted robust tests and documentation for, they would stick them in packages and send them over to me to publish to our original Shiny Server. The problem was: R packages didn’t really mean anything to me at the time. I knew how to install them, but that was about as far as it went. I knew from the Shiny docs that a Shiny app needs certain files (server.R and ui.R or an app.R) file, but that wasn’t what I got, so I’d send it back to the data science team and tell them that I needed those files or I wouldn’t be able to publish it.

More than once I got back a response along the lines of, “but you just need to load it up and then do runApp()”. But, that’s just not how Shiny Server works. Over time, we’ve evolved a set of best practices around when and how to package a Shiny application.

The first step was taking the leap into understanding Shiny and R packages better. It was here that I started to work in the space between data science and IT.

How to package a Shiny application

If you’ve seen the simple app you get when you choose to create a new Shiny application in RStudio, you’ll be familiar with the basic structure of a Shiny application. You need to have a UI object and a server function.

If you have a look inside the UI object you’ll see that it contains the html that will be used for building your user interface. It’s not everything that will get served to the user when they access the web application — some of that is added by the Shiny framework when it runs the application — but it covers off the elements you’ve defined yourself.

The server function defines the server-side logic that will be executed for your application. This includes code to handle your inputs and produce outputs in response.

The great thing about Shiny is that you can create something awesome quite quickly, but once you’ve mastered the basics, the only limit is your imagination.

For our purposes here, we’re going to stick with the ‘geyser’ application that RStudio gives you when you click to create a new Shiny Web Application. If you open up RStudio, and create a new Shiny app — choosing the single file app.R version — you’ll be able to see what we’re talking about. The small size of the geyser app makes it ideal for further study.

If you look through the code you’ll see that there are essentially three components: the UI object, the server function, and the shinyApp() function that actually runs the app.

Building an R package of just those three components is a case of breaking them out into the constituent parts and inserting them into a blank package structure. We have a version of this up on GitHub that you can check out if you want.

The directory layout of the demo project looks like this:

|-- DESCRIPTION
|-- LICENSE
|-- NAMESPACE
|-- R
|   |-- launchApp.R
|   |-- shinyAppServer.R
|   `-- shinyAppUI.R
|-- README.md
|-- inst
|   `-- shinyApp
|       `-- app.R
|-- man
|   |-- launchApp.Rd
|   |-- shinyAppServer.Rd
|   `-- shinyAppUI.Rd
`-- shinyAppDemo.Rproj

Once the app has been adapted to sit within the standard R package structure we’re almost done. The UI object and server function don’t really need to be exported, and we’ve just put a really thin wrapper function around shinyApp() — I’ve called it launchApp() — which we’ll actually use to launch the app. If you install the package from GitHub with devtools, you can see it in action.

library(shinyAppDemo)
launchApp()

This will start the Shiny application running locally.

The approach outlined here also works fine with Shiny Modules, either in the same package, or called from a separate package.

And that’s almost it! The only thing remaining is how we might deploy this app to Shiny server (including Shiny Server Pro) or RStudio Connect.

Publishing your packaged Shiny app

We already know that Shiny Server and RStudio Connect expect either a ui.R and a server.R or an app.R file. We’re running our application out of a package with none of this, so we won’t be able to publish it until we fix this problem.

The solution we’ve arrived at is to create a directory called ‘shinyApp’ inside the inst directory of the package. For those of you who are new to R packaging, the contents of the ‘inst’ directory are essentially ignored during the package build process, so it’s an ideal place to put little extras like this.

The name ‘shinyApp’ was chosen for consistency with Shiny Server which uses a ‘shinyApps’ directory if a user is allowed to serve applications from their home directory.

Inside this directory we create a single ‘app.R’ file with the following line in it:

shinyAppDemo::launchApp()

And that really is it. This one file will allow us to publish our packaged application under some circumstances, which we’ll discuss shortly.

Here’s where having a packaged Shiny app can get tricky, so we’re going to talk you through the options and do what we can to point out the pitfalls.

Shiny Server and Shiny Server Pro

Perhaps surprisingly — given that Shiny Server is the oldest method of Shiny app publication — it’s also the easiest one to use with these sorts of packaged Shiny apps. There are basically two ways to publish on Shiny Server. From your home directory on the server — also known as self-publishing — or publishing from a central location, usually the directory ‘/srv/shiny-server’.

The central benefit of this approach is the ability to update the application just by installing a newer version of the package. Sadly though, it’s not always an easy approach to take.

Apps served from home directory (AKA self-publishing)

The first publication method is from a users’ home directory. This is generally used in conjunction with RStudio Server. In the self-publishing model, Shiny Server (and Pro) expect apps to be found in a directory called ‘ShinyApps’, within the users home directory. This means that if we install a Shiny app in a package the final location of the app directory will be inside the installed package, not in the ShinyApps directory. In order to work around this, we create a link from where the app is expected to be, to where it actually is within the installed package structure.

So in the example of our package, we’d do something like this in a terminal session:

# make sure we’re in our home directory
cd
# change into the shinyApps directory
cd shinyApps
# create a link from our app directory inside the package
ln -s /home/sellorm/R/x86_64-pc-linux-gnu-library/3.4/shinyAppDemo/shinyApp ./testApp

Note: The path you will find your libraries in will differ from the above. Check by running .libPaths()[1] and then dir(.libPaths()[1]) to see if that’s where your packages are installed.

Once this is done, the app should be available at ‘http://<server-address>:3838//’ and can be updated by updating the installed version of the package. Update the package and the updates will be published via Shiny Server straight away.

Apps Server from a central location (usually /srv/shiny-server)

This is essentially the same as above, but the task of publishing the application generally falls to an administrator of some sort.

Since they would have to transfer files to the server and log in anyway, it shouldn’t be too much of an additional burden to install a package while they’re there. Especially if that makes life easier from then on.

The admin would need to transfer the package to the server, install it and then create a link — just like in the example above — from the expected location, to the installed location.

The great thing with this approach is that when updates are due to be installed the admin only has to update the installed package and not any other files.

RStudio Connect

Connect is the next generation Shiny Server. In terms of features and performance, it’s far superior to its predecessor. One of the best features is the ability to push Shiny app code directly from the RStudio IDE. For the vast majority of users, this is a huge productivity boost, since you no longer have to wait for an administrator to publish your app for you.

Since publishing doesn’t require anyone to directly log into the server as part of the publishing process, there aren’t really any straightforward opportunities to install a custom package. This means that, in general, publishing a packaged shiny application isn’t really possible.

There’s only one real workaround for this situation that I’m aware of. If you have an internal CRAN-like repository for your custom packages, you should be able to use that to update Connect, with a little work.

You’d need to have your dev environment and Connect hooked up to the same repo. The updated app package needs to be available in that repo and installed in your dev environment. Then, you could publish and then update the single line app.R for each successive package version you publish.

Connect uses packrat under the hood, so when you publish the app.R the packrat manifest will also be sent to the server. Connect will use the manifest to decide which packages are required to run your app. If you’re using a custom package this would get picked up and installed or updated during deployment.

shinyapps.io

It’s not currently possible to publish a packaged application to shinyapps.io. You’d need to make sure your app followed the accepted conventions for creating Shiny apps and only uses files, rather than any custom packages.

Conclusion

Packaging Shiny apps can be a real productivity boon for you and your team. In situations where you can integrate that process into other processes, such as automatically running your unit tests or automated publishing it can also help you adopt devops-style workflows.

However, in some instances, the practice can actually make things worse and really slow you down. It’s essential to understand what the publishing workflow is in your organisation before embarking on any significant Shiny packaging project as this will help steer you towards the best course of action.

If you would like to find out how we can help you with Shiny, get in touch with us: sales@mango-solutions.com

Blogs home Featured Image

After the success of rstudio::conf 2017 this year the conference was back and bigger and better than ever with 1000+ attendees in sunny San Diego. Since the conference, my colleagues and I have been putting the techniques we learned into practice (which is totally why you’re only seeing this blog post now!).

Day 1 – shiny stole the show

The first stream was all things Shiny. With all the hype surrounding Shiny in the past few years, it didn’t disappoint. Joe Cheng spoke at the EARL London Conference in September last year about the exciting new feature allowing users to take advantage of asynchronous programming within Shiny applications through the use of the promises package. It was great to see a live demo of how this new feature can be utilised to scale Shiny apps and reduce wait time. The JavaScript inspired promises are not just Shiny specific and Joe is hoping to release the package on CRAN soon. In the meantime you can check out the package here.

At mango we’re already excited to start streamlining existing and future customer applications using promises. From a business point of view, it’s going to allow us to build more efficient and complex applications.

Straight after Joe was RStudio’s Winston Chang. Winston gave another great demo – this time showing the new features of the shinytest package. As well as improved user interaction, compared to previous shinytestversions, Winston demonstrated the latest snapshot comparison feature. This allows users to compare snapshots side by side when re-running tests and interactively dragging images to compare between them.

This is another potentially exciting breakthrough in the world of Shiny. Testing user interface components of a Shiny app has historically been a manual process, so formalising this process with shinytest will hopefully provide the framework to take proof of concept applications into a validated production ready state. You can check out the latest version here.

We were also excited to hear RStudio have built their own load testing tools which they’ll make available for us as well. Traditional tools for load testing often are incompatible with Shiny apps. RStudio’s main goals were to create something that’s easy to use, can simulate large number of users, and can work well with Shiny apps. It has multiple features in its workflow, such as recording, playback, and result analysis, and we envisage it enabling our customers to get really in-depth metrics on their Shiny apps.

Day 2 – machine learning

Aside from Shiny, a main theme of the conference was undoubtedly machine learning.

Day 2 kicked off with a key note from J.J Allaire, RStudio’s CEO. J.J’s presentation “Machine Learning with R and TensorFlow” was a fantastic insight into how RStudio have been busy in the past year making TensorFlow’s numerical computing library available to the R community. The keras package opens up the whole TensorFlow functionality for easy use in R, without the need to learn Python. It was great to hear TensorFlow explained in such a clear way and has already sparked interest and demand at Mango for our new “Deep Learning with keras in R” course (which, you can attend if you sign up for the EARL London Conference _hint hint)).

The interop stream gave us an insight into the leading technologies integrating with and exciting the world of R. With TensorFlow and Keras being machine learning buzz words at the moment, Javier Luraschi explained how to deploy TensorFlow models for fast evaluation and export using the tfdeploy package. He also highlighted integration with other technologies, such as cloudml and rsconnecthttps://github.com/riga/tfdeploy

Next year the conference has already been announced to run in Austin, Texas. Workshop materials and slides from this year’s conference can be found here.