Building Data-driven Web Applications Using R and Shiny

programming-593312_640

Shiny is a web application framework for the R statistical computing language. It allows interactive applications to be written entirely in R.

While it’s possible to write a general purpose web application using R and Shiny, it’s not the sweet spot of the framework. There are better general purpose web application frameworks—such as ASP.NET MVC.

Where Shiny…well…shines…is when creating web applications that are “analysis-heavy.” Shiny draws on the full power of R, and its dizzying array of packages, making it embarrassingly easy to create interactive data analysis, reporting and visualization applications.

The easiest way to develop Shiny applications is using the RStudio IDE. Shiny is developed by RStudio, so integration with their IDE is first-class.

Once the web application has been developed it has to be deployed so that it can be accessed by the intended users. RStudio has a Shiny server that runs on Linux. It comes in open source and pro flavors. The pro version has security, performance and health monitoring features.

Another hosting option is RStudio’s Shiny cloud service—shinyapps.io. There’s a free development/research tier and then tiers to support most levels of production application. We’ll deploy a simple Shiny application to shinyapps.io in this article.

Shiny app architecture

The basic template for a Shiny application is

library(shiny)

ui <- fluidPage()

server <- function(input, output) {}

shinyApp(ui = ui, server = server)

fluidPage configures the user interface. It contains static items (text, images, etc) and input controls (text boxes, buttons, etc).

server <- function(input, output) {} defines the core functionality of the application. It defines how user input is transformed into results (output).

All your Shiny apps should follow this basic architecture.

Creating the user interface

We are going to create an application that allows us to explore the 2012 General Social Survey data. This dataset is contained within the tigerstats R package. Most of the variables in this dataset are factors so our app will allow pairs of variables to be cross tabulated.

The UI of the app is shown below.

UI of Shiny 2012 General Social Survey cross tabulation app

Let’s build the UI. First we have to install the shiny and tigerstats packages, if they are not already installed. Then we can load them.

library(shiny)
library(tigerstats)

Shiny has a number of layouts you can use in your app. We’re using the sidebar layout for our UI. This takes a sidebarPanel object and a mainPanel object. We’ll also supply a headerPanel to display the title.

ui <- fluidPage(
  headerPanel("2012 General Social Survey cross tabulation"),
  sidebarPanel(),
  mainPanel()
)

We now need to supply content for the sidebar and main panels. We’ll place the dropdown lists for the variables to be cross tabulated in the sidebar.

...
sidebarPanel(
  selectInput("row", "Row variable", names(gss2012), selected = "polviews"),
  selectInput("column", "Column variable", names(gss2012), selected = "sex")
)
...

The main panel will contain the cross tabulation. We actually add a placeholder for it as it’ll be dynamically generated based on the selected variables.

...
mainPanel(
  tableOutput('table')
)
...

This says that we will be rendering a table here and the placeholder has the ID table.

So, our entire UI definition is

ui <- fluidPage(
  headerPanel("2012 General Social Survey cross tabulation"),
  sidebarPanel(
    selectInput("row", "Row variable", names(gss2012), selected = "polviews"),
    selectInput("column", "Column variable", names(gss2012), selected = "sex")
  ),
  mainPanel(
    tableOutput('table')
  )
)

Creating the Shiny server component

We now need to create a cross tabulation based on the variables selected in the UI (row and column).

Shiny uses a reactive approach to bind inputs to code blocks and executes those blocks when their associated inputs change. Results are then bound to output placeholders in the UI (table in our UI).

The server component configuration is very simple.

server <- function(input, output) {
  output$table <- renderTable(prop.table(table(gss2012[, input$row],
gss2012[, input$column])));
}

Using the contents of the row and column controls from our UI (input) we extract the associated variables from our dataset, cross tabulate them (as proportions) and render the result to the table placeholder in our UI.

Finally, we launch our app by specifying the UI and server components as parameters to the shinyApp function.

shinyApp(ui = ui, server = server)

Save your application as app.R. The filename is important—Shiny recognises this file as the main script of a Shiny app.

At the top of the RStudio editor pane you should see a Run App button. This will launch your app in a web browser. If you don’t see the button then run the script as usual.

Select some variables using the dropdown controls and watch the cross tabulation update. An interactive data explorer app!

Publishing to shinyapps.io

So far, so good. But the app is only available on your local machine…and you need RStudio to run it. Not much use to the average manager. We need to publish our application on the web.

As mentioned earlier, we’re going to publish to RStudio’s Shiny cloud hosting service—shinyapps.io. You need to sign up for a free account to get started. Do that before continuing.

In RStudio

  1. Go to Tools > Global Options… > Publishing
  2. Click the Connect… button
  3. Follow the instructions in the dialog to get your connection details from your shinyapps.io account
  4. Enter the details into the text area on the dialog
  5. Close all open dialogs

Now we’re ready to publish our app to shinyapps.io. Select File > Publish…, name your app in the resulting dialog and confirm with the Publish button.

Wait patiently while it builds and uploads your app then voilà! Your web browser will be launched displaying your newly published app.

You can use my finished app on shinyapps.io and the full code is available as a Gist.

If you are interested in learning more about R, Learning Tree provides the following courses

Type to search blog.learningtree.com

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.