开始使用免费开始使用

添加一个下拉选择输入

向 Shiny 应用添加输入分两步:先在 UI 中添加一个 ___Input("x") 函数,然后在服务器端通过 input$x 读取其值。

例如,若要让用户从列表中选择一种动物,您可以使用 selectInput,并通过 input$animal 引用所选的值:

selectInput(
  'animal', 
  'Select Animal', 
  selected = 'Cat', 
  choices = c('Dog', 'Cat')
)

在本练习中,您将构建一个 Shiny 应用。通过添加一个输入,让用户选择性别,从而可视化按性别划分的最受欢迎的前 10 个名字。

本练习是课程的一部分

使用 R 构建 Shiny Web 应用

查看课程

练习说明

  • 添加一个名为 "sex" 的下拉选择输入,让用户在 "M" 和 "F" 之间选择,默认值为 "F"。
  • 更新服务器端代码,根据所选性别获取前 10 个名字,而不是仅使用 "F"。

交互式实操练习

通过完成这段示例代码来试试这个练习。

ui <- fluidPage(
  titlePanel("What's in a Name?"),
  # CODE BELOW: Add select input named "sex" to choose between "M" and "F"

  # Add plot output to display top 10 most popular names
  plotOutput('plot_top_10_names')
)

server <- function(input, output, session){
  # Render plot of top 10 most popular names
  output$plot_top_10_names <- renderPlot({
    # Get top 10 names by sex and year
    top_10_names <- babynames %>% 
      # MODIFY CODE BELOW: Filter for the selected sex
      filter(sex == "F") %>% 
      filter(year == 1900) %>% 
      slice_max(prop, n = 10)
    # Plot top 10 names by sex and year
    ggplot(top_10_names, aes(x = name, y = prop)) +
      geom_col(fill = "#263e63")
  })
}

shinyApp(ui = ui, server = server)
编辑并运行代码