9.3 An example Shiny App

Now that you have the basics, add the following code, run the app and check out the results:

Replace your UI code with this:

ui <- fluidPage(
  selectInput("dataset", label = "Dataset", choices = ls("package:datasets")),
  verbatimTextOutput("summary"),
  tableOutput("table")
)

Here youre providing a layout function with fluidPage() to set up the visual structure of the page, an input control for user interaction with selectInput(), verbatimTextOutput() and tableOutput() are output controls that tell Shiny where to put rendered output. Spend some time poking around to see how each of these functions operate under the hood.

Replace your server code with this:

server <- function(input, output, session) {
  output$summary <- renderPrint({
    dataset <- get(input$dataset, "package:datasets")
    summary(dataset)
  })
  
  output$table <- renderTable({
    dataset <- get(input$dataset, "package:datasets")
    dataset
  })
}

Defining the server function is like putting a brain in the app. Now it can receive signals and tell the app what to do. The left-hand side of the assignment operator (<-), output$ID, indicates that you’re providing the recipe for the Shiny output with that ID. The right-hand side of the assignment uses a specific render function to wrap some code that you provide. Each render{Type} function is designed to produce a particular type of output (e.g. text, tables, and plots), and is often paired with a {type}Output function. For example, in this app, renderPrint() is paired with verbatimTextOutput() to display a statistical summary with fixed-width (verbatim) text, and renderTable() is paired with tableOutput() to show the input data in a table.

Run the app now and see what happens when you change the input! You will joyfully notice that the summary and table update whenever you change the input data from the dropdown menu. This dependency is created implicitly because we’ve referred to input$dataset within the output functions. input$dataset is populated with the current value of the UI component with id dataset, and will cause the outputs to automatically update whenever that value changes. This is a fundamental concept in Shiny known as reactivity, outputs automatically react when their inputs change. There is much to learn about this!