Interactive Web Apps with Shiny

Article · 3:00

The UI and server split, the reactive flow and how to reason about it, dashboards, and getting an app deployed.

Shiny lets you write a web application in R with no HTML, CSS or JavaScript. It is the reason an analyst can hand a stakeholder something they can click rather than a chart that is already out of date.

An app has two halves. The UI describes the page - inputs, outputs, layout - and is R functions that generate HTML. The server is a function taking input, output and session that says how outputs are computed from inputs. shinyApp(ui, server) joins them.

The idea that makes Shiny work, and the one to spend time on, is reactivity. You do not write "when the slider moves, redraw the chart". You write an expression that uses input$slider, and Shiny builds a dependency graph and re-runs exactly what depended on the thing that changed. That inversion is why Shiny code is short and why it is confusing at first.

Three building blocks cover most needs. reactive() creates a cached expression that recomputes when its inputs change and is read with () like a function - use it for anything two outputs share, so filtering happens once rather than once per chart. render*() functions produce output: renderPlot(), renderTable(), renderText(), each paired with an *Output() in the UI. observeEvent() runs code for its side effect when something specific happens - a button press, a file upload - and returns nothing.

The commonest beginner mistake is putting the same filter() in three render functions. Each re-runs independently, so the work happens three times. Put it in one reactive() and call it from all three.

isolate() reads a reactive value without depending on it, which is how you stop a plot redrawing on every keystroke. req() stops an expression quietly when an input is not ready yet, which removes most of the red errors a new app shows on startup. bindEvent() makes a reactive wait for a button rather than updating live.

For layout, fluidPage() with sidebarLayout() covers simple apps. For a dashboard, bslib is the modern choice - page_sidebar(), card(), value_box() - built on Bootstrap 5 and actively developed. shinydashboard is the older option, widely used and still fine.

Deploying: rsconnect::deployApp() pushes to shinyapps.io, which has a free tier. For anything internal, Posit Connect or a self-hosted Shiny Server; and a Docker image works anywhere.

library(shiny)
library(bslib)
library(ggplot2)
library(dplyr)

# ---- UI: what the page looks like -----------------------------------
ui <- page_sidebar(
  title = "Fuel economy",

  sidebar = sidebar(
    selectInput("class", "Vehicle class",
                choices  = sort(unique(mpg$class)),
                selected = "compact",
                multiple = TRUE),
    sliderInput("displ", "Engine size",
                min = 1.5, max = 7, value = c(1.5, 7), step = 0.1),
    checkboxInput("smooth", "Show trend line", TRUE),
    actionButton("refresh", "Recalculate", class = "btn-primary")
  ),

  layout_columns(
    value_box(title = "Cars shown",  value = textOutput("n")),
    value_box(title = "Mean highway mpg", value = textOutput("avg"))
  ),
  card(card_header("Engine size against economy"), plotOutput("scatter")),
  card(card_header("By manufacturer"), tableOutput("table"))
)

# ---- Server: how outputs are computed from inputs -------------------
server <- function(input, output, session) {

  # ONE reactive, read by everything below. Without this the same
  # filter runs in each render function - three times the work, and
  # three chances for them to disagree.
  filtered <- reactive({
    req(input$class)           # wait quietly until it exists, rather
                               # than throwing a red error on startup
    mpg |>
      filter(class %in% input$class,
             displ >= input$displ[1],
             displ <= input$displ[2])
  })

  output$n   <- renderText({ nrow(filtered()) })        # () to read it
  output$avg <- renderText({ round(mean(filtered()$hwy), 1) })

  output$scatter <- renderPlot({
    p <- ggplot(filtered(), aes(displ, hwy, colour = class)) +
      geom_point(size = 2, alpha = 0.8) +
      labs(x = "Displacement (l)", y = "Highway mpg") +
      theme_minimal(base_size = 13)

    if (input$smooth) p <- p + geom_smooth(method = "lm", se = FALSE)
    p
  })

  output$table <- renderTable({
    filtered() |>
      summarise(n = n(), mean_hwy = mean(hwy), .by = manufacturer) |>
      arrange(desc(n))
  })

  # observeEvent: run for the SIDE EFFECT, return nothing.
  observeEvent(input$refresh, {
    showNotification(paste("Recalculated at", format(Sys.time(), "%H:%M:%S")),
                     type = "message")
  })

  # A reactive that waits for the button instead of updating live:
  #   expensive <- reactive({ slow_thing(input$x) }) |>
  #     bindEvent(input$refresh)
  #
  # isolate() reads a value WITHOUT depending on it, which is how you
  # stop a plot redrawing on every keystroke in a text box:
  #   output$p <- renderPlot({ input$go; plot(isolate(input$text)) })
}

shinyApp(ui, server)

# ---- Deploying -------------------------------------------------------
# rsconnect::deployApp()              # shinyapps.io; free tier exists
#
# A deployed app runs on a server that does not have your files, your
# working directory, or the packages you forgot you had installed. The
# two things that break a first deployment, in order:
#   1. a path that only exists on your machine  -> use here::here()
#   2. a package used but never library()'d     -> renv, next topic

Discussion

No questions on this topic yet. Sign in to ask the first one.