Your First Shiny App
In Lesson 2 you put Maya's six bakery shops on one screen and linked the tiles with crosstalk: click a shop and every chart narrows to it. But crosstalk has a hard edge. It only ever filters rows that were already computed when the page was built. It can never run new R after the page loads.
So when Maya asks a planning question, "if I raise prices by 10%, what would my projected revenue be?", crosstalk is stuck. That number does not exist anywhere on the page yet. Someone has to run R again with the new 10% to compute it. That is exactly what Shiny does, and the engine that makes it happen is called reactivity.
The dashboard below is the goal. Move the Price increase control and watch the projected-revenue boxes and both charts recompute, live, each from a fresh calculation.
By the end of this lesson you will be able to:
- Say what reactive means: an output that recomputes by itself when an input it depends on changes
- Name the three parts of every Shiny app,
ui,server, andshinyApp(), and write the smallest one - See that the work inside an app is ordinary R you already write, just placed where Shiny can re-run it
- Trace how the reactive graph re-runs only what changed, and decide when you truly need Shiny
Prerequisites: you can run R and load a package with library(), you have built a ggplot and computed a summary in the ggplot2 course, and you have finished Lesson 1 and Lesson 2, where you met crosstalk and its limit: it filters, it does not re-run R. Every new term is defined as it appears.
What "reactive" means
Think of a spreadsheet. Maya types each shop's monthly revenue into cells, and in one more cell she writes a formula that adds them up: =SUM(B2:B7), which reads $227,000. Now she edits Old Town from 53,000 to 60,000. She does not re-run anything. The total updates itself, instantly, to $234,000. The total depends on those cells, so the moment they change, it recomputes.
That self-updating is reactivity, and a Shiny app is built from exactly three kinds of thing:
- An input: a value the user sets, here a slider for the price increase. (The editable cells.)
- An output: something shown back, here the projected-revenue number and a chart. (The total cell.)
- A reaction: the R code that turns inputs into outputs. (The
SUMformula.)
The magic word is depends. You never tell Shiny "recompute now." You just declare which output is built from which input, and Shiny recomputes it for you the instant that input changes.
Everything below is built from Maya's six shops. Each lesson runs in a fresh R session, so build that data right here (run this once, then every later block can use it):