開始使用免費開始

下拉選單

你已經看過如何在 shinyApp 中加入下拉選單。這讓使用者能從多個選項中挑一個,同時只佔用少量版面。如果應用程式已經有很多其他元件,這會是很不錯的 UI 設計。

在本練習中,資料已儲存在 sleep,而名為 p 的圖也已經建立並儲存。同時已載入 shinytidyverse 函式庫。當你完成程式碼後,可以在 HTML Viewer 中開啟 shinyApp,以獲得更完整的檢視。

本練習屬於課程

使用 shinydashboard 建立儀表板

檢視課程

練習說明

  • 放置一個 selectInput(),提供兩個選項「Plot」與「Table」。
  • 放置 plotOutput()tableOutput(),名稱分別為「plot」與「table」。
  • 在伺服器中加入圖形輸出。
  • 在伺服器中加入表格輸出。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

ui <- fluidPage(
  titlePanel("Sleeping habits in America"), 
  # Place a selectInput with two choices, "Plot" and "Table"
  ___("choice", "Choose an output",
              choices = ___),
  # Place plot and table outputs called "plot" and "table"
  ___("plot"), ___)
server <- function(input, output) {
  # Add renderPlot
  output$plot <- ___({
    if(input$choice == "Plot") p
  })
  # Add renderTable
  output$___ <- ___({
    if(input$choice == "Table") sleep
  }) }
shinyApp(ui, server)
編輯並執行程式碼