允许查看 "All" 洲别
在添加洲别选择器之前,Shiny 应用会显示所有洲的数据。现在添加了洲别选择器,数据可以按洲查看。但如果用户并不想按某个特定洲筛选,而是希望查看所有洲呢?不幸的是,添加洲别选择器后,这个能力被移除了。
可以修改 selectInput() 函数的 choices 参数,在洲别列表中添加一个额外的值。当选择该值时,就可以关闭洲别筛选。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
在下拉选择中添加一个用于选择所有洲别的 "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)