Check if all options are selected in pickerInput

Hello,

I have this really basic example with pickerInput to represent my problem. I essentially only want the filter comparison to take place if not all the items are selected on the list. If all the items are selected, I simply want it to allocate data to df. I have a lot of filter conditions that can't all do the comparison for %in% ongoing. Any help?

library(shinyWidgets)
library(shiny)


reactiveStorage <- reactiveValues(df = NULL)


data <- data.frame(
               Cat = c("a", "b", "c", "d", "a", "b", "d"),
              Var1 = c(31, 20, 94, 33, 69, 43, 35),
              Var2 = c(86, 23, 96, 69, 26, 51, 93),
              Var3 = c(4, 43, 91, 47, 86, 76, 80),
              Var4 = c(20, 23, 72, 70, 35, 96, 37),
              Var5 = c(64, 31, 56, 64, 36, 77, 55)
 ) 

ui <- fluidPage(
  pickerInput(
    inputId = "somefiltervalue",
    label = "A label",
    choices = c("a", "b","c","d"),
    selected = c(1,2,3,4),
    multiple = TRUE,
    options = list(`actions-box` = TRUE)
  ),
  actionButton("compare","Filter"),
  tableOutput("value")
)

server <- function(input, output) {
    output$value <- renderTable({
      req(input$compare)
      df <- data %>% filter(Cat %in%(input$somefiltervalue))
    })
   
}

shinyApp(ui, server)

Created on 2020-10-07 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)

How about something like this?

choices <- c("a", "b", "c", "d")

ui <- fluidPage(
  pickerInput(
    inputId = "somefiltervalue",
    label = "A label",
    choices = choices,
    selected = c(1, 2, 3, 4),
    multiple = TRUE,
    options = list(`actions-box` = TRUE)
  ),
  actionButton("compare", "Filter"),
  tableOutput("value")
)

server <- function(input, output) {
  output$value <- renderTable({
    req(input$compare)
    if (identical(choices, sort(input$somefiltervalue))) {
      data
    } else {
      data %>% filter(Cat %in% (input$somefiltervalue))
    }
  })
}
2 Likes

@hadley, thanks so much for the solution :slight_smile:

I just wanted to ask - is there any unforeseen consequences if you were to perform the comparison based on length as a proxy? Would it potentially lead you astray?

Why would you want to do that? It’s unlikely to be practically faster and you’d need to carefully analyse it to make sure that the weakened check was always correct for your use cases.

1 Like

I thought it might be potentially faster but as you say your proposed solution is safer and there likely is no additional benefit in this instance. Thank you :slight_smile:

I just remembered that right function for this situation is setequal()

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.