开始使用免费开始使用

添加洲选择器:下拉选择输入

当可供用户选择的选项很多时,单选按钮会占用较多空间,可能并不理想。选择输入(也称为"下拉列表")也可以让用户从一组选项中做出选择,但形式更为紧凑。使用选择输入时,所有选项都会显示在一个可滚动的列表中,即使有很多选项也可以使用。

与单选按钮类似,选择输入也有 choicesselected 参数。此外,选择输入还有一个 multiple 参数,将其设为 TRUE 时,用户可以一次选择多个值。

本题已提供上一个练习的 Shiny 应用代码,并做了少量修改。

本练习是课程的一部分

案例研究:使用 R 的 Shiny 构建 Web 应用

查看课程

练习说明

  • 在 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)
编辑并运行代码