Shiny inside RMarkdown: what's the boilerplate?

I was having a wander through R Markdown: The Definitive Guide, and I found an interesting example: embedding Shiny app in an R Markdown document.

title: "A Shiny Document"
output: html_document
runtime: shiny

A standard R plot can be made interactive by wrapping
it in the Shiny `renderPlot()` function. The `selectInput()`
function creates the input widget to drive the plot.

```{r eruptions, echo=FALSE}
  'breaks', label = 'Number of bins:',
  choices = c(10, 20, 35, 50), selected = 20

  par(mar = c(4, 4, .1, .5))
    faithful$eruptions, as.numeric(input$breaks),
    col = 'gray', border = 'white',
    xlab = 'Duration (minutes)', main = ''

I understand adding runtime: shiny to the YAML, but I was surprised by the chunk content. Usually in Shiny apps, I would expect to see selectInput() given to a layout function like fluidPage(), and renderPlot() would be called inside a server function, and then you'd call shiny() with the layout function call and the server function given to that.

Here, selectInput() and renderPlot() are thrown together in the chunk. Is it simply that the rest of the boilerplate isn't required in simple cases, or is R Markdown or knitr doing something behind the scenes to ensure these two functions are hooked up properly?


According to the Intro to Interactive Documents (these things have gone by a few different names and I don't think all the docs are aligned right now):

When you run an interactive document, rmarkdown extracts the code in your code chunks and places them into a pseudo server.R file. R Markdown uses the html output of the markdown file as an index.html file to place the reactive elements into.

As a result, outputs in one code chunk can use widgets and reactive expressions that occur in other code chunks.

Since the R Markdown document provides a layout for the app, you do not need to write a ui.R file.

And that's about the limit of my understanding! I'd love to hear more about the nitty-gritty from somebody who actually understands it inside and out. :upside_down_face:

ETA: I think this where rmarkdown creates the shiny ui boilerplate?

1 Like

I've used the tagged external HTML template approach to build Shiny UI before, so that makes sense! Thanks @jcblum :smile: