開始使用免費開始

加入洲別選擇器:select input

當可供使用者選擇的選項很多時,單選按鈕會佔用大量空間,可能並不理想。選擇式輸入(也稱為「下拉式清單」)能以更精簡的方式,讓使用者從多個選項中挑選其一。使用選擇式輸入時,所有選項會以可捲動的清單呈現,因此即使選項很多也適用。

與單選按鈕類似,選擇式輸入也有 choicesselected 參數。此外,選擇式輸入有 multiple 引數,當設為 TRUE 時,允許使用者一次選取多個值。

以下提供上個練習的 Shiny 應用程式程式碼,已做些微修改。

本練習屬於課程

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

檢視課程

練習說明

  • 在 UI 中加入一個 selectInput(),ID 為「continents」,標籤為「Continents」,且預設洲別為「Europe」。
    • 清單中的選項應包含 gapminder 資料集裡所有不同的洲別。
    • 允許使用者同時選取多個洲別。
  • 在伺服器端加入程式碼,透過對 gapminder 資料集進行子集化(第 23 行),只顯示所選洲別的資料。

動手互動練習

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

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("title", "Title", "GDP vs life exp"),
      numericInput("size", "Point size", 1, 1),
      checkboxInput("fit", "Add line of best fit", FALSE),
      radioButtons("color", "Point color",
                   choices = c("blue", "red", "green", "black")),
      # Add a continent dropdown selector
      ___(___, ___,
                  choices = levels(___),
                  multiple = ___,
                  selected = ___)
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  output$plot <- renderPlot({
    # Subset the gapminder dataset by the chosen continents
    data <- subset(gapminder,
                   ___ %in% ___$continents)

    p <- ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point(size = input$size, col = input$color) +
      scale_x_log10() +
      ggtitle(input$title)
    
    if (input$fit) {
      p <- p + geom_smooth(method = "lm")
    }
    p
  })
}

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