Chapter 7 – Interactive Applications with {shiny}
November 27, 2026
apps/ folder of the course.reactive(), req(), validate(){bslib}: KPIs, graphs, tables, CSV exportA sales dashboard of a real online retailer, built step by step:
{bslib} documentation: layouts, cards, value boxes, themes.{DT} documentation: everything about interactive tables.{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.
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
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).
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.
Every Shiny app has three parts:
ui: the user interface, i.e., what the page looks like (layout, inputs, placeholders for outputs).server: a function describing how outputs are computed from inputs.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.
app.R, in its own folder: one folder = one app.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.
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)"year","scatter".output$scatter is filled with a render function, renderPlot(),input$year.renderPlot({ ... }) is ordinary {dplyr} + {ggplot2} code (chapters 2 and 3).
renderPlot() reads input$year.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").

str(input$<inputId>)).NULL. A button: the number of clicks.app.RAn 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)
output$id <- render*(): never print or return the object directly.plotOutput("scatter") ↔︎ output$scatter), and be unique in the app.input is read-only: input$year <- 2000 is an error.
input$year: move the slider and they are all updated.app.Rlectures 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.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]].)textOutput() under the plot, filled with renderText(), which displays “Data for year XXXX”.input$year in the console. What happens? Why?input$year like this”), and Shiny decides when to run them.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.
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()
})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.filtered(), with parentheses.input$year or input$continents, then shared by both outputs.checkboxGroupInput("continents", ...) and a textOutput("summary") (download full code: app.R).Code:
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
filtered(), hence both outputs. Note that output$summary also reads input$year directly.
filtered().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 silentlyThe output simply stays blank. Useful at start-up, while inputs are not yet available.
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 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 |
Start from apps/02_reactive/app.R ( Download app.R).
validate() line, save, reload, and untick everything again. What do you see?tableOutput() listing the 5 countries with the highest life expectancy among the selected ones. Reuse filtered(). (Hint: slice_max().)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().)A single screen answering recurring questions at a glance.
Classic reading order (Shneiderman 1996): overview first, zoom and filter, then details on demand:
┌─────────────────────────────────────────────────────┐
│ 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.
{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) |
layout_columns()
These examples and those of the next slide are the tabs of one page_navbar(sidebar = ...) app: Download app.R
navset_card_underline()
value_box()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}).
textOutput(): the KPI is updated like any other output.{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.
{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.datatable() as is (row numbers, raw column names, 31889923, no units). Right: the code of the previous slide (readable names, rounded values, $, sorted).app.RdownloadHandler() (recommended)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..xlsx, .png…).Buttons extension of {DT}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.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
{ggplot2}Everything from chapters 3 to 6 works: scales, facets, themes, maps with geom_sf().
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.
{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.app.Rcontinents <- 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")
)
)
)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.
Full code of the dashboard (UI + server): Download app.R
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).
print(...) or message(...) inside a reactive() or render*() to see values in the console as you use the app.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} |
| 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.
shinyApp(ui, server).input$id; outputs are filled with output$id <- render*(); ids match between UI and server.reactive() = a value computed once, shared by several outputs, called with parentheses.req() / validate(need()).page_sidebar() / page_navbar(), layout_columns(), card(), navset_card_underline().value_box(value = textOutput()) + renderText() + {scales} formatting.DTOutput() + renderDT() + datatable() + format*().downloadButton() + downloadHandler().renderPlot() ({ggplot2}), renderPlotly() ({plotly}).app.R.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:
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 |
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.
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 to Use
sum(amount), i.e. sales minus cancellations (cancellations have negative amounts).n_distinct(invoice[!cancelled]).customer_id (customers without an account, NA, are not counted).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).
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.app.R, 3 or 4 questions the sales director would ask. For instance:
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$....
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"));sliderInput() for the number of items in rankings (top products, top countries), from 5 to 25, 10 by default.filtered() so that it uses the countries too. (Hint: if (length(input$country) > 0) ....)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().
kpis() returning a one-row tibble with all the statistics (summarise()), then fill each textOutput() from it (kpis()$orders).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.value_box() to give context, e.g. p("after £716K of cancellations").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%.
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:
{plotly}); aggregate before plotting: never plot a million raw sales lines.summary_table().datatable(): readable column names with units, amounts with formatCurrency(), percentages with formatPercentage(), sorted by net revenue.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.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.Go through this checklist:
Pick one or more:
input$dates - years(1).{rnaturalearth}, and some have no polygon (“European Community”, “Unspecified”).textInput() to keep only the products whose name contains a word (e.g. “CHRISTMAS”): how seasonal are they?actionButton() + bindEvent()). When is this useful?data/sales.rds) and share the link.{bslib}, {DT} and {plotly}.app.R.
Data Visualization with R