Get startedGet started for free

Place different outputs on different tabs

Tabs are useful when you have too much content and want to split it up. To create a tab, you simply wrap UI elements in the tabPanel() function, and you need to supply a title for the tab using the title argument.

In order for tabs to appear in the UI, the tab panels need to be grouped into a tabset "container", by wrapping all the tab panels inside tabsetPanel().

Your task is to add tabs to the Shiny app, such that the inputs and download button are in one tab, the plot is in another tab, and the table is in a third tab. Since this is purely a visual change, all the code changes are to be done in the UI portion only.

This exercise is part of the course

Case Studies: Building Web Applications with Shiny in R

View Course

Exercise instructions

  • Use the tabsetPanel() function to create a container for three tab panels:
    • A first tab for the inputs, and name the tab "Inputs".
    • A second tab that shows the plot, and name the tab "Plot" (line 16).
    • A third tab that shows the table, and name the tab "Table" (line 21).

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

ui <- fluidPage(
    h1("Gapminder"),
    # Create a container for tab panels
    ___(
        # Create an "Inputs" tab
        tabPanel(
            title = ___,
            sliderInput(inputId = "life", label = "Life expectancy",
                        min = 0, max = 120,
                        value = c(30, 50)),
            selectInput("continent", "Continent",
                        choices = c("All", levels(gapminder$continent))),
            downloadButton("download_data")
        ),
        # Create a "Plot" tab
        ___(
            title = "Plot",
            plotOutput("plot")
        ),
        # Create "Table" tab
        ___(
            title = ___,
            DT::dataTableOutput("table")
        )
    )
)

server <- function(input, output) {
  filtered_data <- reactive({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })
  
  output$table <- DT::renderDataTable({
    data <- filtered_data()
    data
  })

  output$download_data <- downloadHandler(
    filename = "gapminder_data.csv",
    content = function(file) {
      data <- filtered_data()
      write.csv(data, file, row.names = FALSE)
    }
  )

  output$plot <- renderPlot({
    data <- filtered_data()
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
Edit and Run Code