How to Create and Deploy a Shiny App

Shiny by RStudio is a framework for turning R code into interactive dashboards. You can build RShiny apps on the DataScience.com Platform within the familiar R or RStudio environment. RShiny app is a collection of .R scripts. This quick tutorial shows how to build an interactive map with RShiny using a dataset on Uber pickups in New York City. For a more extensive tutorial on this topic, visit the related Learning Module: Use Shiny on the DataScience.com Platform

RShiny apps consist of two main components:

  • Code to be executed by the server that will power the app
  • Code defining the UI appearance.

These two components can be defined in separate .R files or combined in one app.R file. In this tutorial, you’ll see an example of both components defined inside one app.R script. This script can also contain any data manipulations needed.

Loading the Data

First, import libraries and set your color theme:

library(tidyr)
library(ggplot2)
library(scales)
library(mapproj)

# Set plotting parameters and import color palettes
set_ds_theme = function() {
  theme_update(panel.background = element_rect(fill = "white", colour = "grey50")
               ,plot.title = element_text(hjust = 0.5))

  # Color palette for continuous data
  cont_ds_palette <<- c('#f7fbff', '#d7ecfd', '#3ba3f8', '#328bd5','#266aa2'
                        ,'#000000')
  cont_gradient <<- colorRampPalette(cont_ds_palette)

  # Palette for discrete/categorical data
  cat_ds_palette <<- c("#3ba3f8", "#afb6bd", "#3eb642", "#6981ef",
                       "#b353b5",     "#e66867")
}
set_ds_theme()

The data is stored on our public AWS S3 bucket. You can access this data with your own set of AWS keys. The data is pulled in and the average number of Uber pickups by location and hour is calculated:

bucketName = "ds-site-static-assets"

s3load('s3://ds-site-static-assets/ds-examples/rshiny/Uber/data/processed_uber_nyc.RData',
                  bucket = bucketName,
                  key=Sys.getenv("AWS_ACCESS_KEY_ID"),
                  secret=Sys.getenv("AWS_SECRET_ACCESS_KEY") )


# Precalculate mean pickups in each location by hour
locID_zone_dim <- unique(agg_data[, c("locationID", "zone")])
agg_data$hour <- as.numeric(agg_data$hour)
geo_pickups <- agg_data %>%
  group_by(locationID, hour) %>%
  summarize(mean_pickup = mean(pickups))

Defining the UI Components

Next, define the main UI components of the app. The goal is to display a heatmap of Uber pickups for NYC. To make the map interactive, you can add a slider filter for changing the hour and a tooltip displaying location coordinates. All of these components will be defined in the UI section:

# Define UI for application that draws a heatmap
ui <- fluidPage(
  # Application title
  titlePanel("Pickups by Hour")

  # Sidebar with a slider input for number of bins
  , sidebarLayout(
    sidebarPanel(
      sliderInput("hour",
                  "Hour of day:",
                  min = 0,
                  max = 23,
                  value = 24)
    )

    # Show a plot of the generated distribution
    , mainPanel(
      plotOutput("NYC_heatmap"
                 , height = 700
                 , width = 700
                 , hover = hoverOpts(id = "plot_hover"))
    )
  )
  # Tooltip
  , fluidRow(column(width = 6
                    , verbatimTextOutput("tooltip")))
)

Defining the Server Component

Finally, define the server component. This will be a function that takes in an input from UI components and returns a plotting output. Each output component corresponds to a chart or UI element. In this case, the app takes in the hour of the day from slider as input and returns a heatmap plot. Another output returned is coordinate values for map tooltip. Note that output names NYC\_heatmap and tooltip get referenced in the UI component.

Finally, tell the app where to find server and UI components. This part can be omitted if the UI and server get defined in two separate .R scripts.

# Run the application
shinyApp(ui = ui, server = server)

Running the App

All of the above snippets are combined in app.R script. To run the app, simply run this from same directory as app.R:

library(shiny)
runApp("app.R")

Publishing the App

Now the app is ready to be published as an Output. To publish, click on the Quick Actions button and select Publish a Shiny App:

../_images/5645f12-publish_uber_lite_pv6.14.7.png

Give your app a name and a short description and click Continue:

../_images/f13088d-publish_shiny_name_pv6.14.7.png

Select your repo branch, app directory, compute resource size, and provide a commit message. Then click Publish:

../_images/2d5b7de-publish_shiny_dialog_pv6.14.7.png

Warning

You must specify a directory, not a .R file when publishing a Shiny dashboard.

Now your app is visible under Outputs. Users can view and interact with the app without having to start a new R session:

../_images/1ebf4e0-final_app_uber_lite_pv6.14.7.png