19.3 Embedded Shiny apps

Besides embedding individual Shiny inputs and outputs in R Markdown, it is also possible to embed a standalone Shiny application within a document. There are two ways to do this:

  1. Defining the application inline using the shinyApp() function; or

  2. Referring to an external application directory using the shinyAppDir() function.

Both functions are available in the shiny package (not rmarkdown), which will be automatically loaded when runtime: shiny is specified in the YAML metadata of the document, so you do not have to call library(shiny) to load shiny (although it does not hurt if you load a package twice).

19.3.1 Inline applications

This example uses an inline definition:

```{r, echo=FALSE}
shinyApp(

  ui = fluidPage(
    selectInput("region", "Region:",
                choices = colnames(WorldPhones)),
    plotOutput("phonePlot")
  ),

  server = function(input, output) {
    output$phonePlot = renderPlot({
      barplot(WorldPhones[,input$region]*1000,
              ylab = "Number of Telephones", xlab = "Year")
    })
  },

  options = list(height = 500)
)
```

Note the use of the height parameter to determine how much vertical space the embedded application should occupy.

19.3.2 External applications

This example embeds a Shiny application defined in another directory:

```{r, echo = FALSE}
shinyAppDir(
  system.file("examples/06_tabsets", package="shiny"),
  options = list(width = "100%", height = 700)
)
```

Note that in all of R code chunks above, the chunk option echo = FALSE is used. This is to prevent the R code within the chunk from rendering to the output document alongside the Shiny components.