Read-me-first Shiny tutorial IV: understanding the ui variable

Even the simplest Shiny program has two parts, a ui variable and a server function. When you’re just getting started, it appears these parts are of equal importance. But eventually you realize that it’s all about the server function. The ui is such a nothing that in this tutorial we’ll nearly get rid of it.

In the following code I’ve started once again with the Old Faithful sample code, but truncated the ui to a single output and moved the rest of the ui inside the server function. The code changes are in bold:

library(shiny)

# Define UI for application that draws a histogram
ui <- uiOutput("uiStub")

# Define server logic required to draw a histogram
server <- function(input, output) {
   output$uiStub <- renderUI(
      fluidPage(
         # Application title
         titlePanel("Old Faithful Geyser Data"),
 
         # Sidebar with a slider input for number of bins 
         sidebarLayout(
            sidebarPanel(
               sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
            ),
 
            # Show a plot of the generated distribution
            mainPanel(
               plotOutput("distPlot")
            )
         )
      )
   )
   output$distPlot <- renderPlot({
      # generate bins based on input$bins from ui.R
      x <- faithful[, 2] 
      bins <- seq(min(x), max(x), length.out = input$bins + 1)
 
      # draw the histogram with the specified number of bins
      hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })
}

# Run the application 
shinyApp(ui = ui, server = server)

The big advantage of coding the ui this way is that it becomes more obvious that you can change the entire page by redefining output$uiStub. To old school HTML coders like me, the typical Shiny ui variable appears to limit you to just a single page. On that single page you have the ability to update defined parts of the page in response to inputs. But by mostly getting rid of the ui variable, as shown in this code, it becomes clear that Shiny can support web sites with multiple pages.

Another feature of this new version of Old Faithful is that it makes clear that outputs can be nested. In this code, the distPlot output is embedded inside the uiStub output. Again, Shiny allows you to update either the whole page (output$uiStub) or just a section of a page (output$distPlot). Your Shiny project can be a single page or multiple pages, each page can have sections that update, and even those sections can be further subdivided using nested outputs.

For now, this is the final lesson in this read-me-first Shiny tutorial. The four posts are about the major things I wish I had known when I started learning Shiny.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *