在 reactive shiny 中实现 'Select All' 选项

Implement 'Select All' option in reactive shiny

我正在构建一个闪亮的应用程序,它会根据用户的选择显示 table。我有一个名为 'stat' 的 table,它的形式是

Team      Season   wins  loss  draws
Arsenal   1992-93   18    12    14
Arsenal   1993-94   21    10    7 
Liverpool 1992-93   22    6     12
Liverpool 1993-94   19    13    10
 All        All     0     0     0

我需要根据所选球队和赛季筛选数据。当赛季选择 'All' 时,table 应该显示所有赛季的数据,反之亦然。

我已经尝试了下面的一些代码,但它没有按预期工作。

#UI part
selectInput("club", "Select Club", choices = stat$Team),
                 selectInput("season", "Select Season", choices = 
 stat$Season)

#server part
server <- output$statdata <- renderTable({
  teamfilter <- subset(stat, (stat$Team == input$club) & 
                         (stat$Season==input$season))
})

  observe({
    if("Select All" %in% input$club)
      selected_choices = stat$Team[-1]
    else
      selected_choices = input$club
    updateSelectInput(session, "club", selected = selected_choices)

})

有人可以建议我一个正确的代码,或者告诉我是否需要任何更改才能使代码正常工作。

这是一个 full-working 示例,展示了如何将 "All" 合并到 selectInput 中:

library(shiny)
dat <- mtcars
app <- shinyApp(
  ui = shinyUI(
    pageWithSidebar(
      headerPanel("Simple Test"),
      sidebarPanel(
        selectInput("cyl", "Cylinders", choices = c("All", sort(unique(dat$cyl)))),
        selectInput("gear", "Gears", choices = c("All", sort(unique(dat$gear))))
      ),
      mainPanel(
        shiny::tableOutput("out")
      )
    )
  ),
  server = function(input, output, session) {
    filtered <- reactive({
      rows <- (input$cyl == "All" | dat$cyl == input$cyl) &
        (input$gear == "All" | dat$gear == input$gear)
      dat[rows,,drop = FALSE]
    })
    output$out <- renderTable(filtered())
  }
)

这利用了 R 的回收:虽然 input$gear == "All" returns 是单个逻辑,dat$gear == input$gear returns 是一个向量,只要 [=] 中的行数33=]。因为第一个logical的长度是1,所以和第二个vector一样长被回收。这意味着 input$gear == "All" 实际上是一个长度为 "nrow(dat)" 的向量,并且总是全 TRUE 或全 FALSE。如果为真,其他 $gear 比较中的 none 很重要(我在掩饰 NA 比较);当为假时,其他 $gear 比较是相关的。

回收示范:

1 == 1
# [1] TRUE
1 == 2
# [1] FALSE

1 == 1:5
# [1]  TRUE FALSE FALSE FALSE FALSE

1 == 1 | 1 == 1:5
# [1] TRUE TRUE TRUE TRUE TRUE
1 == 2 | 1 == 1:5
# [1]  TRUE FALSE FALSE FALSE FALSE