In the previous chapter, we presented the Shiny framework of RStudio in detail. Besides building complete web applications, there is also the possibility of integrating entire Shiny applications into R Markdown documents and presentations. Since we have already learned all the basic functions of R Markdown, and the use and logic of Shiny, we will focus on the following lines of integrating a simple Shiny app into an R Markdown file.
In order for Shiny and R Markdown to work together, the argument, runtime: shiny
must be added to the YAML header of the file. Of course, the RStudio IDE offers a quick way to create a new Shiny document presentation. Click on the new file, choose R Markdown
, and in the popup window select Shiny from the left-hand side menu. In the Shiny menu, you can decide whether you want to start with a Shiny Document option or a Shiny Presentation option:
After choosing the
Shiny Document option, a prefilled .Rmd
file opens. It is different from the known R Markdown interface in that there is the Run Document button instead of the knit button and icon.
The prefilled .Rmd
file produces an R Markdown document with a working and interactive Shiny application. You can change the number of bins in the plot and also adjust the bandwidth. All these changes get rendered in real time, directly in your document.
Also, when you click on
Shiny Presentation in the selection menu, a prefilled .Rmd
file opens. Because it is a presentation, the output format is changed to ioslides_presentation
in the YAML header. The button in the code pane is now called Run Presentation:
Otherwise, Shiny Presentation looks just like normal R Markdown presentations. The Shiny app gets embedded in a slide and you can again interact with the underlying data of the application:
Of course, the question arises that how is it possible to embed a whole Shiny application onto an R Markdown document without the two usual basic files, ui.R
and server.R
? In fact, the rmarkdown
package creates an invisible server.R
file by extracting the R code from the code chunks. Reactive elements get placed into the index.html
file of the HTML output, while the whole R Markdown document acts as the ui.R
file.