開始使用免費開始

允許檢視所有("All")大洲

在加入大洲選擇器之前,Shiny 應用程式會顯示所有大洲的資料。現在加上選擇器後,就能按大洲檢視資料。可是如果使用者不想篩選特定大洲,而是想看全部呢?很不巧的是,加入大洲選擇器之後,就失去顯示全部的能力了。

可以修改 selectInput() 函式的 choices 引數,為大洲清單新增一個值。當選到這個值時,就把大洲篩選關閉。

本練習屬於課程

案例研究:使用 R 的 Shiny 建置網頁應用程式

檢視課程

練習說明

在選擇輸入中加入可選的「All」大洲。當選到該選項時,不要進行任何大洲篩選。具體而言:

  • 在 UI 中提供給選擇輸入的選項清單裡,加入「All」這個值。
  • 在 server 端,用 if 敘述檢查大洲是否設為「All」。如果選了「All」,就不要對大洲做任何篩選(第 20 行)。

動手互動練習

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

ui <- fluidPage(
  h1("Gapminder"),
  sliderInput(inputId = "life", label = "Life expectancy",
              min = 0, max = 120,
              value = c(30, 50)),
  # Add an "All" value to the continent list
  selectInput("continent", "Continent",
              choices = c(___, levels(gapminder$continent))),
  tableOutput("table")
)

server <- function(input, output) {
  output$table <- renderTable({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    # Don't subset the data if "All" continent are chosen
    if (___) {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })
}

shinyApp(ui, server)
編輯並執行程式碼