Course homepage

Data Visualization with R

Chapter 7 – Interactive Applications with {shiny}

Ewen Gallic

November 27, 2026

Disclaimers

  1. I used Claude Opus 5.5 to help generate these slides.
  2. Shiny apps need a running R session: they cannot run inside these slides. The code shown here is not evaluated; the screenshots come from the apps provided in the apps/ folder of the course.

Roadmap for This Chapter

How Shiny Works

  1. What is a Shiny app, and when do you need one?
  2. The two ingredients: UI + server
  3. Inputs and outputs
  4. Reactivity: reactive(), req(), validate()
  5. Building a dashboard with {bslib}: KPIs, graphs, tables, CSV export
  6. Structuring, debugging and sharing an app

Final Exercise

  1. A sales dashboard of a real online retailer, built step by step:

    • filters (inputs),
    • key performance indicators (KPIs),
    • graphs,
    • a summary table that can be exported as CSV.

Packages Used in This Chapter

install.packages(c(
  "shiny", # the web application framework
  "bslib", # modern layouts: sidebars, cards, value boxes (Bootstrap 5)
  "bsicons", # Bootstrap icons, for the value boxes
  "DT", # interactive tables
  "plotly", # interactive graphs
  "gapminder",
  "readxl"
))

Key References

What Is a Shiny App?

From a Report to an Application

  • An application lets the reader ask their own questions: pick a year, a region, a threshold… and the numbers, graphs and tables are recomputed.
  • {shiny} builds such web applications in R only: no HTML, CSS or JavaScript required. Everything you have learned so far ({dplyr}, {ggplot2}, {sf}) can be reused inside an app.

Exploratory or Communicative?

A Shiny app is often used to explore (an analyst browsing the data) or to monitor (a dashboard checked every week).

Each graph inside the app should still be a good communicative graph: clear message, labels, units.

How It Works: Two Programs Talking to Each Other

flowchart LR
    U["<b>Web browser</b><br/><br/><br/>user interface (UI):<br/>sliders, menus, graphs, tables"]
    S["<b>R session</b><br/><br/><br/>server function:<br/>filters, summaries, ggplots"]
    U -- "the user moves a slider<br/><br/>input$year = 1977" --> S
    S -- "updated graph, text, table" --> U

    style U fill:#e6f0ff,stroke:#3366cc
    style S fill:#ffe5cc,stroke:#cc6600

  • The UI is a web page displayed in a browser. When the user changes an input, the new value is sent to R.
  • The server is an R session: it re-runs the code that depends on the changed input and sends the new outputs back to the page.

An R Session Must Be Running

A notebook, such as a Quarto HTML report, is a static file.

By contrast, a Shiny app needs an R process for as long as somebody uses it.

This R process can either be on your computer, or on a server (see “Sharing Your App” at the end).

When Do You Need Shiny?

  • If you want to let the reader choose filters, recompute statistics, download the data they selected, a Shiny app can help.

Start From a Working Analysis

Never start a Shiny app from scratch!

First write a script that produces your table and your graph for one choice of parameters (e.g., year 2007).

An app is that script, in which a few hard-coded values (2007) are replaced by inputs (input$year), that will set the value provided by the user.

The Main Ingredients of a Shiny App

The Smallest Possible App

library(shiny)
library(bslib)

ui <- page_fluid(
  "Hello, world!"
)

server <- function(input, output, session) {
}

shinyApp(ui = ui, server = server)

Every Shiny app has three parts:

  1. ui: the user interface, i.e., what the page looks like (layout, inputs, placeholders for outputs).
  2. server: a function describing how outputs are computed from inputs.
  3. shinyApp(ui, server): glues both and launches the app.

{shiny} and {bslib}

{shiny} provides the engine (inputs, outputs, reactivity). {bslib} provides the modern page layouts (page_fluid(), page_sidebar(), page_navbar()), cards and value boxes.

Running an App

  • Save the code in a file named app.R, in its own folder: one folder = one app.
lectures/
└── apps/
    ├── 01_first-app/
    │   └── app.R
    └── 02_reactive/
        └── app.R
  • Launch it with the Run App button of RStudio (top of the script), or from the console:
shiny::runApp("apps/01_first-app")
  • The console prints Listening on http://127.0.0.1:XXXX and the app opens in a viewer or your browser.

The Console Is Busy While the App Runs

You cannot run other commands while the app is running. Stop it with the red Stop button (or Esc in the console). After editing app.R, save and click Reload app.

Step 1: One Input, One Output

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

ui <- page_sidebar(
  title = "Gapminder explorer",
  sidebar = sidebar(
    sliderInput(
      inputId = "year", label = "Year",
      min = 1952, max = 2007, value = 2007, step = 5, sep = ""
    )
  ),
  plotOutput(outputId = "scatter")
)

server <- function(input, output, session) {
  output$scatter <- renderPlot({
    gapminder |>
      filter(year == input$year) |>
      ggplot(
        mapping = aes(
          x = gdpPercap, y = lifeExp, 
          colour = continent, size = pop)
      ) +
      geom_point(alpha = 0.6) +
      scale_x_log10(labels = scales::label_dollar(accuracy = 1)) +
      scale_size_area(max_size = 15, guide = "none") +
      labs(
        x = "GDP per capita (log scale)", y = "Life expectancy (years)",
        colour = "Continent", title = paste("Year:", input$year)
      ) +
      theme_minimal(base_size = 16)
  })
}

shinyApp(ui, server)
  • UI: a page with a sidebar, made of
    • an input: a slider whose id is "year",
    • an output placeholder: a plot whose id is "scatter".
  • Server:
    • output$scatter is filled with a render function, renderPlot(),
    • inside it, the current value of the slider is read with input$year.
  • The code inside renderPlot({ ... }) is ordinary {dplyr} + {ggplot2} code (chapters 2 and 3).

Step 1: The Result

  • Move the slider: the plot is redrawn automatically.
  • You never wrote “when the slider moves, redraw the plot”: Shiny detected that renderPlot() reads input$year.
  • This automatic dependency tracking is called reactivity (next section).

Inputs: Collecting the User’s Choices

Every input function takes an inputId (a unique name) and a label; in the server, its value is input$<inputId>. Navigate to the Shiny components webpage to see those inputs in action.

Function Widget Value in input$...
sliderInput() Slider (one value, or a range) Number (or 2 numbers)
selectInput(), selectizeInput() Drop-down menu (multiple = TRUE for several) Character (vector)
checkboxGroupInput() Several check boxes Character vector, NULL if nothing is ticked
radioButtons() One choice among a few Character
checkboxInput(), input_switch() One check box / switch TRUE / FALSE
dateRangeInput() Two calendars Date vector of length 2
numericInput(), textInput() Free entry Number / character
actionButton() Button A counter, increased at each click

Named Choices

choices = c("Day" = "day", "Week" = "week", "Month" = "month"): names are displayed, values are sent to R (input$unit is "week").

Outputs: Placeholders and Render Functions

An output always comes as a pair: a placeholder in the UI, and a render function in the server, linked by the same id.

UI placeholder Server: output$id <- ... Displays
plotOutput("id") renderPlot({ ... }) A {ggplot2} (or base R) graph
textOutput("id") renderText({ ... }) Text
tableOutput("id") renderTable({ ... }) A simple static table
DTOutput("id") renderDT({ ... }) An interactive table ({DT})
plotlyOutput("id") renderPlotly({ ... }) An interactive graph ({plotly})
uiOutput("id") renderUI({ ... }) UI elements built in the server
downloadButton("id") downloadHandler(...) A button to download a file

Three Rules (Most Bugs Come From Breaking One of Them)

  1. Fill outputs with output$id <- render*(): never print or return the object directly.
  2. The id must match exactly between UI and server (plotOutput("scatter") ↔︎ output$scatter), and be unique in the app.
  3. input is read-only: input$year <- 2000 is an error.

Task 1: Your First App

  1. In your lectures project, create the folder apps/01_first-app/ and an app.R file containing the code of Step 1 ( Download app.R). Run the app.
  2. Change the default year to 1952, and make the slider move by steps of 10 years. Which years of the data can no longer be selected? Put the step back to 5.
  3. Add a selectInput() with id "yvar" letting the user choose the variable on the y axis among "lifeExp" and "gdpPercap". (Hint: in aes(), use y = .data[[input$yvar]].)
  4. Add a textOutput() under the plot, filled with renderText(), which displays “Data for year XXXX”.
  5. Stop the app. Try to run input$year in the console. What happens? Why?

Reactivity

A Different Way of Programming

  • A usual R script is imperative: lines run from top to bottom, once, in the order you wrote them.
  • A Shiny server is declarative: you give recipes (“this plot is made from input$year like this”), and Shiny decides when to run them.
  • When an input changes, Shiny invalidates everything that depends on it, and re-runs only those pieces of code.

The Spreadsheet Analogy

In a spreadsheet, if cell B1 contains = A1 * 2, changing A1 updates B1 automatically, and only the cells that depend on A1 are recomputed. Inputs are like A1; outputs and reactive expressions are like B1.

Duplicated Code: A Problem

Suppose we add a short text summary above the plot. Without precautions, the filtering step is written (and computed) twice:

output$summary <- renderText({
  data_year <- gapminder |> filter(year == input$year, continent %in% input$continents)
  paste(nrow(data_year), "countries")
})

output$scatter <- renderPlot({
  data_year <- gapminder |> filter(year == input$year, continent %in% input$continents)
  ggplot(data_year, aes(x = gdpPercap, y = lifeExp)) + geom_point()
})
  • If you change the filter, you must remember to change it everywhere.
  • With a large dataset, the same filter is computed several times for nothing.
  • The solution: a reactive expression.

Reactive Expressions: reactive()

server <- function(input, output, session) {

  # Reactive expression: computed once, reused by every output that calls it
  filtered <- reactive({
    validate(need(length(input$continents) > 0, "Select at least one continent."))
    
    gapminder |>
      filter(year == input$year, continent %in% input$continents)
  })

  output$summary <- renderText({
    paste0(
      nrow(filtered()), " countries in ", input$year,
      ", median life expectancy: ",
      round(median(filtered()$lifeExp), 1), " years."
    )
  })

  output$scatter <- renderPlot({
    filtered() |>
      ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent, size = pop)) +
      geom_point(alpha = 0.6) +
      scale_x_log10(labels = scales::label_dollar(accuracy = 1)) +
      scale_colour_discrete(drop = FALSE) +
      scale_size_area(max_size = 15, guide = "none") +
      labs(
        x = "GDP per capita (log scale)", y = "Life expectancy (years)",
        colour = "Continent"
      ) +
      theme_minimal(base_size = 16)
  })
}
  • reactive({ ... }) creates a reactive expression: a value computed from inputs.
  • It is used like a function: filtered(), with parentheses.
  • It is cached: computed once after each change of input$year or input$continents, then shared by both outputs.
  • It is lazy: computed only if an output needs it.
  • The UI gains a checkboxGroupInput("continents", ...) and a textOutput("summary") (download full code: app.R).

Code:

The Reactive Graph

Shiny keeps track of who depends on whom. For the app of the previous slide:

flowchart LR
    Y["<b>input$year</b>"]
    C["<b>input$continents</b>"]
    F["<b>filtered()</b><br/>reactive expression"]
    T["<b>output$summary</b>"]
    P["<b>output$scatter</b>"]

    Y --> F
    C --> F
    Y --> T
    F --> T
    F --> P

    style Y fill:#e6f0ff,stroke:#3366cc
    style C fill:#e6f0ff,stroke:#3366cc
    style F fill:#fff5cc,stroke:#cc9900
    style T fill:#e5f5e5,stroke:#339933
    style P fill:#e5f5e5,stroke:#339933

  • Inputs (blue) → reactive expressions (yellow) → outputs (green).
  • Ticking a continent invalidates filtered(), hence both outputs. Note that output$summary also reads input$year directly.

Seeing the Graph of Your Own App

Install {reactlog}, run reactlog::reactlog_enable(), launch your app and play with it. Then, either press Ctrl + F3 (Cmd + F3 on a Mac) in the app, or stop the app and run:

shiny::reactlogShow()

An interactive picture of the reactive graph appears in your browser.

Step 2: The Result

  • The summary and the plot are always consistent: they come from the same filtered().
  • Untick all the continents: instead of an obscure error, the message “Select at least one continent.” is displayed (next slide).

Guarding Against Empty or Missing Inputs

Inputs are not always usable: nothing ticked in a check box group (NULL), an empty text field, a start date after the end date… Two tools stop a computation early:

req(): stop silently

output$scatter <- renderPlot({
  req(input$continents)   # NULL -> stop here
  ...
})

The output simply stays blank. Useful at start-up, while inputs are not yet available.

validate(need()): stop with a message

filtered <- reactive({
  validate(need(
    length(input$continents) > 0,
    "Select at least one continent."
  ))
  ...
})

The message is displayed in place of every output that depends on filtered(). Better for the user.

Test the Extreme Cases

Before sharing an app, try to break it: untick everything, choose a period with no data, select an option that returns zero rows. A red error message in an output means a case you did not handle.

The Reactive Toolbox

The first three are needed in almost every app; the last two are good to know.

Tool Purpose Example
render*() Compute an output output$plot <- renderPlot(...)
reactive() Compute a value reused by several outputs filtered <- reactive(...)
req(), validate(need()) Stop when inputs are not usable req(input$file)
bindEvent() Wait for a click before recomputing reactive(...) |> bindEvent(input$go)
observe(), observeEvent() Perform a side effect (not an output) update the choices of an input, show a notification
# Recompute the (slow) model only when the user clicks the "Update" button
model <- reactive({
  lm(lifeExp ~ log(gdpPercap), data = filtered())
}) |>
  bindEvent(input$update)

Task 2: Reactivity

Start from apps/02_reactive/app.R ( Download app.R).

  1. Run the app and untick all the continents. Then comment out the validate() line, save, reload, and untick everything again. What do you see?
  2. Add a third output: a tableOutput() listing the 5 countries with the highest life expectancy among the selected ones. Reuse filtered(). (Hint: slice_max().)
  3. Add a checkboxInput("log_x", "Log scale for GDP", value = TRUE) and use it to switch the log scale of the x axis on and off. (Hint: build the plot in an object p, then if (input$log_x) p <- p + scale_x_log10().)
  4. Which outputs are recomputed when you tick “Log scale”?

Building a Dashboard

What Is a Dashboard?

  • A single screen answering recurring questions at a glance.

  • Classic reading order (Shneiderman 1996): overview first, zoom and filter, then details on demand:

    1. filters (inputs) in a sidebar,
    2. a row of KPIs (Key Performance Indicators),
    3. graphs: trends, comparisons, distributions,
    4. a table with the details, that can be exported.
┌─────────────────────────────────────────────────────┐
│ Title                            Overview │ Table   │
├────────────┬────────────────────────────────────────┤
│ FILTERS    │ ┌────────┐ ┌────────┐ ┌────────┐       │
│            │ │  KPI   │ │  KPI   │ │  KPI   │  ...  │
│ Period     │ └────────┘ └────────┘ └────────┘       │
│ [.. - ..]  │ ┌──────────────────┐ ┌───────────────┐ │
│            │ │                  │ │ Table         │ │
│ Countries  │ │      Graph       │ │               │ │
│ [.......]  │ │                  │ │ [Download CSV]│ │
│            │ └──────────────────┘ └───────────────┘ │
└────────────┴────────────────────────────────────────┘

Everything From Previous Chapters Still Applies

One question per graph, a title that states the message, labelled axes with units, the same colour for the same category in every graph, colour-blind-safe palettes, rates rather than counts when comparing groups of different sizes.

Layouts With {bslib}

Function Role
page_sidebar(title, sidebar = sidebar(...), ...) A single page with a sidebar for the inputs
page_navbar(title, sidebar = ..., nav_panel("A", ...), nav_panel("B", ...)) Several pages, chosen in a top navigation bar
layout_columns(col_widths = c(6, 6), ...) Places elements side by side, on a grid of 12 columns
card(card_header("Title"), ..., full_screen = TRUE) A box with a header; full_screen = TRUE adds an “expand” icon
navset_card_underline(nav_panel("Tab 1", ...), ...) Tabs inside a card: several graphs in the same space
value_box(title, value, showcase = bs_icon("...")) A KPI tile (next slide)
page_*(theme = bs_theme(primary = "#1e3a5f")) Changes the main colour; bs_theme(bootswatch = "flatly") applies a ready-made theme (bootswatch.com)
page_sidebar(
  title = "My dashboard",
  sidebar = sidebar(sliderInput("year", "Year", 1952, 2007, 2007)),
  layout_columns(
    col_widths = c(8, 4),                                   # 8/12 and 4/12 of the width
    card(card_header("A graph"), plotOutput("scatter")),
    card(card_header("A table"), DTOutput("table"))
  )
)

Layouts in Action (1): Grids

layout_columns()

# widths out of 12, one call per row
layout_columns(col_widths = c(4, 8), card_a, card_b)
layout_columns(col_widths = c(3, 3, 6), card_c, card_d, card_e)
layout_columns(col_widths = 12, card_f)

layout_column_wrap()

layout_column_wrap(
  width = 1/3, fill = FALSE,       # 3 boxes per row
  value_box(...), value_box(...), value_box(...)
)
card(card_header("A graph below the KPIs"), plotOutput("trend"))

These examples and those of the next slide are the tabs of one page_navbar(sidebar = ...) app: Download app.R

Layouts in Action (2): Tabs and Local Sidebars

# several outputs, as tabs of one card
navset_card_underline(
  title = "Life expectancy", full_screen = TRUE,
  nav_panel("Over time",    plotOutput("trend")),
  nav_panel("Distribution", plotOutput("hist")),
  nav_panel("Table",        tableOutput("table"))
)

layout_sidebar() in a card()

card(
  card_header("GDP per capita vs. life expectancy"),
  layout_sidebar(
    sidebar = sidebar(           # this sidebar belongs to the card only
      position = "right",
      radioButtons(...), checkboxInput(...)
    ),
    plotOutput("scatter")
  )
)

KPIs With value_box()

UI

layout_columns(
  fill = FALSE,   # boxes keep their natural height
  value_box(
    title    = "Countries",
    value    = textOutput("kpi_n"),
    showcase = bs_icon("globe2"),
    theme    = "primary"
  ),
  value_box(
    title    = "Total population",
    value    = textOutput("kpi_pop"),
    showcase = bs_icon("people-fill"),
    theme    = "secondary"
  )
)

Icons: search icons.getbootstrap.com and pass the name to bs_icon() ({bsicons}).

Server

fmt_big <- scales::label_number(
  scale_cut = scales::cut_short_scale(),
  accuracy  = 0.1
)

output$kpi_n   <- renderText(nrow(filtered()))
output$kpi_pop <- renderText(
  fmt_big(sum(as.numeric(filtered()$pop)))
)
  • The value is a textOutput(): the KPI is updated like any other output.
  • Format numbers for humans with {scales}: 6.3B rather than 6251013179, 76.3% rather than 0.76321. Useful helpers: scales::comma(), scales::percent(), scales::label_dollar().

What Makes a Good KPI?

A KPI answers a question in one number, has a unit, is defined unambiguously (revenue before or after cancellations?) and, when possible, comes with a reference (previous year, target). Three to five KPIs are enough.

Interactive Tables With {DT}

output$table <- renderDT({
  filtered() |>
    mutate(
      country, continent, lifeExp, 
      pop_m = pop / 1e6, gdpPercap,
      .keep = "none"
    ) |>
    arrange(desc(lifeExp)) |>
    datatable(
      rownames = FALSE,
      colnames = c("Country", "Continent", "Life exp.", "Pop. (M)", "GDP/cap."),
      options = list(pageLength = 8)
    ) |>
    formatRound(c("lifeExp", "pop_m"), digits = 1) |>
    formatCurrency("gdpPercap", digits = 0)
})
  • datatable() gives sorting, searching and pagination for free; DTOutput("table") is the UI placeholder.
  • formatRound(), formatPercentage(), formatCurrency() change how numbers are displayed, without changing the data.
  • A table is a visualisation too: round numbers, give readable column names with units, sort by the most relevant column.

Tables in Action: Default vs. Formatted

  • Same data, same filters. Left: datatable() as is (row numbers, raw column names, 31889923, no units). Right: the code of the previous slide (readable names, rounded values, $, sorted).
  • Both get sorting, search and pagination for free. Download app.R

Exporting a Table as CSV: Two Ways

# UI
downloadButton("download_csv", "Download data (CSV)")

# Server
output$download_csv <- downloadHandler(
  filename = \() paste0("gapminder_", input$year, ".csv"),
  content  = \(file) readr::write_csv(filtered(), file)
)
  • filename: a function returning the name of the file (it can depend on the inputs).
  • content: a function writing the file to the path file provided by Shiny.
  • Exports exactly the reactive data, whatever the number of rows displayed. Works for any format (.xlsx, .png…).

2. The Buttons extension of {DT}

output$table <- renderDT(
  datatable(
    filtered(),
    extensions = "Buttons",
    options = list(
      dom = "Bfrtip",   # B = Buttons, f = filter, r, t = table, i = info, p = pages
      buttons = c("copy", "csv")
    )
  ),
  server = FALSE
)
  • The export happens in the browser: it exports the rows the browser knows about.
  • With the default server = TRUE, the browser only receives the current page: the CSV then contains only the 10 rows displayed!
  • server = FALSE sends the whole table to the browser: fine for a summary table, not for a million sales lines.

Exporting: Try the Three Options

Export from each table and count the rows of the file: 1,704 (downloadHandler()), 1,704 (server = FALSE)… and only 8 with the default server = TRUE. Download app.R

Graphs: Static or Interactive

{ggplot2}

# UI
plotOutput("scatter")

# Server
output$scatter <- renderPlot({
  filtered() |>
    ggplot(aes(x = gdpPercap, y = lifeExp)) +
    geom_point() +
    scale_x_log10()
})

Everything from chapters 3 to 6 works: scales, facets, themes, maps with geom_sf().

{plotly}

# UI
plotlyOutput("scatter")

# Server
output$scatter <- renderPlotly({
  p <- filtered() |>
    ggplot(aes(x = gdpPercap, y = lifeExp,
               text = country)) +
    geom_point() +
    scale_x_log10()
  ggplotly(p, tooltip = "text")
})

Tooltips, zoom and legend filtering, at the cost of a slower rendering.

Aggregate Once, Plot Many Times

If several graphs use the same summary (e.g. statistics per week), compute it in a reactive() and call it from each render*(). Plotting a million raw sales lines is slow and unreadable: summarise first, as you would in a report.

Graphs in Action: Static vs. Interactive

  • Same {ggplot2} code, two render functions. Left: an image, redrawn by R at each change. Right: a widget, with tooltips (here, Japan), zoom and pan in the browser.
  • These graphs keep the default labels on purpose: polish them as you learned (titles, axis labels, units). Download app.R

Step 3: A Small Dashboard (UI)

continents <- levels(gapminder$continent)

# Number formatters (from {scales}), e.g. 6.3B, $6,124
fmt_big    <- scales::label_number(scale_cut = scales::cut_short_scale(), accuracy = 0.1)
fmt_dollar <- scales::label_dollar(accuracy = 1)

ui <- page_sidebar(
  title = "Gapminder dashboard",
  sidebar = sidebar(
    sliderInput(
      inputId = "year", label = "Year",
      min = 1952, max = 2007, value = 2007, step = 5, sep = ""
    ),
    checkboxGroupInput(
      inputId = "continents", label = "Continents",
      choices = continents, selected = continents
    ),
    downloadButton(outputId = "download_csv", label = "Download data (CSV)")
  ),
  # Row 1: KPIs
  layout_columns(
    fill = FALSE,
    value_box(
      title = "Countries", value = textOutput("kpi_n"),
      showcase = bs_icon("globe2"), theme = "primary"
    ),
    value_box(
      title = "Total population", value = textOutput("kpi_pop"),
      showcase = bs_icon("people-fill"), theme = "secondary"
    ),
    value_box(
      title = "Median life expectancy", value = textOutput("kpi_life"),
      showcase = bs_icon("heart-pulse"), theme = "success"
    ),
    value_box(
      title = "Median GDP per capita", value = textOutput("kpi_gdp"),
      showcase = bs_icon("cash-coin"), theme = "info"
    )
  ),
  # Row 2: graph + table
  layout_columns(
    col_widths = c(6, 6),
    card(
      full_screen = TRUE,
      card_header("Life expectancy vs. GDP per capita"),
      plotOutput("scatter")
    ),
    card(
      full_screen = TRUE,
      card_header("Countries"),
      DTOutput("table")
    )
  )
)

Step 3: A Small Dashboard (Server)

server <- function(input, output, session) {

  filtered <- reactive({
    validate(need(length(input$continents) > 0, "Select at least one continent."))
    gapminder |>
      filter(year == input$year, continent %in% input$continents)
  })

  # --- KPIs ---
  output$kpi_n    <- renderText(nrow(filtered()))
  output$kpi_pop  <- renderText(fmt_big(sum(as.numeric(filtered()$pop))))
  output$kpi_life <- renderText(paste(round(median(filtered()$lifeExp), 1), "years"))
  output$kpi_gdp  <- renderText(fmt_dollar(median(filtered()$gdpPercap)))

  # --- Graph ---
  output$scatter <- renderPlot({
    filtered() |>
      ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent, size = pop)) +
      geom_point(alpha = 0.6) +
      scale_x_log10(labels = scales::label_dollar(accuracy = 1)) +
      scale_colour_discrete(drop = FALSE) +
      scale_size_area(max_size = 15, guide = "none") +
      labs(x = "GDP per capita (log scale)", y = "Life expectancy (years)", colour = NULL) +
      theme_minimal(base_size = 15) +
      theme(legend.position = "bottom")
  })

  # --- Table ---
  output$table <- renderDT({
    filtered() |>
      transmute(country, continent, lifeExp, pop_m = pop / 1e6, gdpPercap) |>
      arrange(desc(lifeExp)) |>
      datatable(
        rownames = FALSE,
        colnames = c("Country", "Continent", "Life exp.", "Pop. (M)", "GDP/cap."),
        options = list(pageLength = 8)
      ) |>
      formatRound(c("lifeExp", "pop_m"), digits = 1) |>
      formatCurrency("gdpPercap", digits = 0)
  })

  # --- CSV export of the filtered data ---
  output$download_csv <- downloadHandler(
    filename = \() paste0("gapminder_", input$year, ".csv"),
    content  = \(file) readr::write_csv(filtered(), file)
  )
}

Why as.numeric() in the Population KPI?

pop is stored as integers. The world population (about 6.3 billion) exceeds the largest integer R can store (about 2.1 billion): sum() would return NA with an “integer overflow” warning. Converting to double first avoids it.

Step 3: The Result

Full code of the dashboard (UI + server): Download app.R

Where Should Each Piece of Code Go?

Location in app.R When does it run? Put there…
Top of the file, outside server Once, when the app starts library() calls, reading and preparing the data, helper functions, lists of choices
Inside server, outside any reactive Once per user (each browser tab) Rarely needed
Inside reactive() / render*() Each time an input it uses changes Filtering, summarising, plotting: what depends on inputs

Do Not Read Your Data Inside a Render Function

renderPlot({ read_csv("big_file.csv") |> ... }) re-reads the file each time the user moves a slider. Read and clean the data once, at the top of the file, then only filter in the reactive expressions.

Growing Apps

When app.R gets long, move helper functions to .R files in a sub-folder named R/: Shiny sources them automatically when the app starts. For large apps, learn about modules (see Wickham (2021), ch. 19).

Debugging a Shiny App

  • Errors are printed in the R console, and a red message replaces the faulty output. Read them!
  • Add print(...) or message(...) inside a reactive() or render*() to see values in the console as you use the app.
  • Add browser() inside a render function: the app pauses there and you can inspect input$... and filtered() in the console.
Symptom Likely cause
An output never appears, no error The id differs between UI and server (plotOutput("plot") vs output$plt), or the id is used twice
Can't access reactive value 'year' outside of reactive consumer input$year used outside reactive(), render*() or observe()
argument is of length zero, missing value where TRUE/FALSE needed An input is NULL or empty: add req() or validate(need())
object of type 'closure' is not subsettable filtered$pop instead of filtered()$pop: missing parentheses
could not find function "page_sidebar" library(bslib) missing, or old version of {bslib}

Sharing Your App

Option How Comment
Send the folder Zip app.R + data; the recipient runs shiny::runApp() Needs R and the packages
Posit Connect Cloud Publish button in RStudio ({rsconnect}), or deploy from a GitHub repository Free plan available (shinyapps.io no longer exists)
Shinylive shinylive::export("myapp", "site"), then host the static files (e.g. GitHub Pages) R runs in the browser (WebAssembly): no server, but not every package works and the data are downloaded by the visitor
Posit Connect / Shiny Server Installed by your institution or company Access control, private data

shinyapps.io Is Being Retired

Many tutorials still point to shinyapps.io. Posit has announced that it remains active until 31 December 2026, after which accounts and apps are migrated to Posit Connect Cloud. Start directly with Connect Cloud.

Everything in the App Folder Can Be Published

Do not deploy confidential data, passwords or API keys stored in your project folder.

Wrap-up

Concepts

  • An app = a UI (the page) + a server (R code) + shinyApp(ui, server).
  • Inputs are read with input$id; outputs are filled with output$id <- render*(); ids match between UI and server.
  • Reactivity: Shiny tracks dependencies and re-runs only what is affected by a change.
  • reactive() = a value computed once, shared by several outputs, called with parentheses.
  • Handle empty inputs with req() / validate(need()).

Recipes

  • Layout: page_sidebar() / page_navbar(), layout_columns(), card(), navset_card_underline().
  • KPIs: value_box(value = textOutput()) + renderText() + {scales} formatting.
  • Tables: DTOutput() + renderDT() + datatable() + format*().
  • CSV export: downloadButton() + downloadHandler().
  • Graphs: renderPlot() ({ggplot2}), renderPlotly() ({plotly}).
  • Prepare data once, at the top of app.R.

Final Exercise: A Sales Dashboard

Task 3: Overview

You have just been hired as a data analyst by a UK-based online retailer selling gift-ware, mostly to wholesalers (shops, resellers) in the UK and abroad. The sales director wants a dashboard to follow sales: how much do we sell, when, which products, to whom, and where? You work on the company’s real transaction data (Online Retail II, Chen (2012)).

Your dashboard must contain:

  1. Filters: period, countries, time unit of the graphs (day / week / month), number of items in rankings.
  2. At least 4 KPIs (value boxes), updated with the filters.
  3. At least 3 graphs, each answering a different question, with appropriate chart types.
  4. A summary table that can be exported as CSV.

A starter folder is provided: exercise/starter/ (app.R + prepare_data.R). The app runs as it is: complete every TODO.

Part Content Time
A Plan: questions, KPIs, graphs 15 min
B Inputs and filtered data 20 min
C KPIs 20 min
D Graphs 35 min
E Summary table, CSV export 20 min
F Polish and test 10 min

The Data: Where It Comes From

  • All the transactions of the retailer between 1 December 2009 and 9 December 2011, published on the UCI Machine Learning Repository (licence CC BY 4.0). One row = one product line of an invoice.
  • prepare_data.R is run automatically at the first launch of the app (about a minute): it downloads the Excel file (45 MB, one sheet per year), cleans it, and saves data/sales.rds. Later launches read the .rds file directly.
Cleaning step Lines left
Raw file (two sheets) 1,067,371
Remove exact duplicated lines 1,033,036
Keep products only (remove postage, bank charges, manual adjustments…) 1,027,056
Remove lines with a zero price 1,021,128

Real Data Are Messy

Cancellations are invoices starting with "C" (with negative quantities), 22% of the lines have no customer ID, some products are spelled in several ways, and Excel turns invoice numbers into numbers unless you say otherwise (read_excel(..., col_types = ...)). Read prepare_data.R: each cleaning step is commented.

If the Download Fails

Download online_retail_II.xlsx from the UCI page of the dataset, put it in the data/ folder of the app, and launch the app again.

The Data: What It Looks Like

glimpse(sales): 1,021,128 rows, 13 columns.

$ invoice     <chr> "489434", "489434", "489434", "489434", "489434", "48943…
$ datetime    <dttm> 2009-12-01 07:45:00, 2009-12-01 07:45:00, 2009-12-01 07…
$ date        <date> 2009-12-01, 2009-12-01, 2009-12-01, 2009-12-01, 2009-12…
$ weekday     <ord> Tue, Tue, Tue, Tue, Tue, Tue, Tue, Tue, Tue, Tue, Tue, T…
$ hour        <int> 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9,…
$ stock_code  <chr> "85048", "79323P", "79323W", "22041", "21232", "22064", …
$ product     <chr> "15CM CHRISTMAS GLASS BALL 20 LIGHTS", "PINK CHERRY LIGH…
$ quantity    <dbl> 12, 12, 12, 48, 24, 24, 24, 10, 12, 12, 24, 12, 10, 18, …
$ price       <dbl> 6.95, 6.75, 6.75, 2.10, 1.25, 1.65, 1.25, 5.95, 2.55, 3.…
$ amount      <dbl> 83.40, 81.00, 81.00, 100.80, 30.00, 39.60, 30.00, 59.50,…
$ cancelled   <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, …
$ customer_id <int> 13085, 13085, 13085, 13085, 13085, 13085, 13085, 13085, …
$ country     <chr> "United Kingdom", "United Kingdom", "United Kingdom", "U…
  • amount = quantity × price, in pounds sterling (£); it is negative for cancellations.
  • customer_id is NA for customers without an account; country is the country of the customer (43 countries, the United Kingdom first).

Definitions Used in the Dashboard

Definitions to Use

  • Net revenue: sum(amount), i.e. sales minus cancellations (cancellations have negative amounts).
  • Orders: number of distinct invoices that are not cancellations, n_distinct(invoice[!cancelled]).
  • Average order value: net revenue / orders.
  • Customers: number of distinct customer_id (customers without an account, NA, are not counted).
  • Cancellation rate: value of the cancelled lines / value of the sold lines.

Agree on Definitions First

In a company, the first question asked about a dashboard is always “how is this number computed?”. Two analysts computing “revenue” with and without cancellations will present two different numbers to the same director. Write your definitions down, in the app itself if possible (an “About” page).

Part A: Plan Before You Code

  1. Copy the folder exercise/starter/ into your project (e.g. apps/sales/), open app.R and run it. The first launch downloads and prepares the data. Read prepare_data.R meanwhile.
  2. Write, as comments at the top of app.R, 3 or 4 questions the sales director would ask. For instance:
    • How much do we sell, and how does it evolve? Is there a seasonal pattern?
    • Which products drive our revenue?
    • Which international markets matter most?
    • When do our customers place their orders? What does a typical order look like?
  3. For each question, decide what answers it best: a KPI, a graph (which type?), or the table.
  4. Draw a sketch of your dashboard on paper (sidebar, KPI row, graphs, table). Decide whether you need one page (page_sidebar()) or several (page_navbar(), as in the starter file).

Prototype Outside Shiny

Before writing any render*(), write the {dplyr} + {ggplot2} code of each graph in a separate script, with fixed values (e.g. France, year 2011), using sales <- readRDS("apps/sales/data/sales.rds"). Once it works, paste it into the app and replace the fixed values by filtered() and input$....

Part B: Inputs and Filtered Data

  1. In the sidebar, keep the period input of the starter file, and add:
    • a selectizeInput() to select one or several countries among country_choices (sorted by number of sales lines). When nothing is selected, the app should use all countries (hint: options = list(placeholder = "All countries"));
    • radioButtons() to show revenue by day, week or month (named choices: c("Day" = "day", "Week" = "week", "Month" = "month"));
    • a sliderInput() for the number of items in rankings (top products, top countries), from 5 to 25, 10 by default.
  2. Complete the reactive expression filtered() so that it uses the countries too. (Hint: if (length(input$country) > 0) ....)
  3. Check that the “Net revenue” KPI of the starter file changes with the filters. Select France, from 2011-01-01 to 2011-12-09: you should get £173,587.

Not Every Input Is a Filter

The time unit and the ranking size do not change which sales are selected, only how they are displayed. Use them in the graphs, not in filtered().

Part C: KPIs

  1. Add at least three value boxes next to “Net revenue”. Suggestions: orders, average order value, customers, cancellation rate, units sold, revenue per customer, number of products sold.
  2. Rather than computing each KPI separately, create one reactive expression kpis() returning a one-row tibble with all the statistics (summarise()), then fill each textOutput() from it (kpis()$orders).
  3. Format each value for humans, with its unit: scales::label_dollar(prefix = "£", scale_cut = scales::cut_short_scale()) turns 18926266 into £19M; scales::comma(), scales::percent(). Choose an icon for each box on icons.getbootstrap.com.
  4. Use the optional text of value_box() to give context, e.g. p("after £716K of cancellations").
  5. Choose a start date after the end date. Do your KPIs display NaN or £NaN? Make them display something sensible instead (e.g. "-").

Sanity Check

All countries, whole period: net revenue £18.9M, 39,516 orders, 5,852 customers, average order value £479, cancellation rate 3.6%.

Part D: Graphs

Build at least three graphs answering your questions of Part A (in tabs: navset_card_underline()). Some ideas:

Question Possible graph Chapter
How do sales evolve? Is there a seasonal pattern? Line chart of net revenue by day / week / month (floor_date(date, input$unit)), UK vs. rest of the world 3
Which products drive revenue? Top N products, sorted horizontal bar chart 5
Which international markets matter? Top N countries. The UK (85% of revenue) crushes the scale: exclude it and say so in a subtitle 5
When do customers order? Heatmap of the number of orders by weekday × hour (geom_tile()) 4
What does a typical order look like? Distribution of order values (one value per invoice), log scale, with the median 4

Requirements:

  • every graph has a title stating its message (e.g. “Sales peak every November”), axis labels with units (£), and the same colour for the same category in every graph (e.g. UK vs. rest of the world);
  • at least one graph uses the time unit, one the ranking size, and one is interactive ({plotly}); aggregate before plotting: never plot a million raw sales lines.

Part E: Summary Table and CSV Export

  1. Replace the raw table of the starter file by a summary table with one row per country: net revenue, orders, customers, average order value, units sold, cancellation rate. Store it in a reactive expression summary_table().
  2. Display it with datatable(): readable column names with units, amounts with formatCurrency(), percentages with formatPercentage(), sorted by net revenue.
  3. Add a downloadButton() and a downloadHandler() exporting summary_table() as a CSV file. The file name should contain the selected period, e.g. sales_by_country_2011-01-01_2011-06-30.csv.
  4. Open the downloaded file. Does it contain all the rows, even those not displayed on the first page of the table? Does the sum of its net revenue column match your KPI?
  5. Bonus: add radioButtons() to choose the grouping variable of the table (country, product, month). (Hints: mutate(month = format(floor_date(date, "month"), "%Y-%m")), then group_by(.data[[input$table_by]]).) Add a second button exporting the filtered sales lines themselves.

Part F: Polish and Test

Go through this checklist:

Going Further (Optional)

Pick one or more:

  • Year-on-year comparison: next to each KPI, show the change compared with the same period one year earlier (e.g. “+8% vs. previous year”). Hint: input$dates - years(1).
  • Map: net revenue by country (chapter 6). Some country names must be matched to {rnaturalearth}, and some have no polygon (“European Community”, “Unspecified”).
  • New vs. returning customers: for each month, the revenue from customers buying for the first time vs. from customers who had already ordered.
  • Product search: a textInput() to keep only the products whose name contains a word (e.g. “CHRISTMAS”): how seasonal are they?
  • “Apply” button: recompute everything only when the user clicks a button (actionButton() + bindEvent()). When is this useful?
  • Deploy your app on Posit Connect Cloud (include data/sales.rds) and share the link.

Summary of the Chapter

What You Can Now Do

  • Turn an analysis script into an application: hard-coded values become inputs.
  • Explain how a Shiny app works: browser ↔︎ R session, UI + server, reactive graph.
  • Build a dashboard with filters, KPIs, graphs and tables, using {bslib}, {DT} and {plotly}.
  • Let users export exactly the data they selected.

What Stays the Same

  • An app is only as good as its graphs: everything from chapters 3 to 6 applies to each output.
  • Prepare the data before visualising it (chapter 2), and here, once, at the top of app.R.
  • Choose the representation according to the question, not to what the tool makes easy.

References

Chen, Daqing. 2012. “Online Retail II.” UCI Machine Learning Repository. https://doi.org/10.24432/C5CG6D.
Fay, Colin, Sébastien Rochette, Vincent Guyader, and Cervan Girard. 2021. Engineering Production-Grade Shiny Apps. Chapman; Hall/CRC. https://engineering-shiny.org/.
Shneiderman, Ben. 1996. “The Eyes Have It: A Task by Data Type Taxonomy for Information Visualizations.” In Proceedings 1996 IEEE Symposium on Visual Languages, 336–43. IEEE.
Wickham, Hadley. 2021. Mastering Shiny: Build Interactive Apps, Reports, and Dashboards Powered by r. O’Reilly Media. https://mastering-shiny.org/.