Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiny selectInput to select all from dropdown

Tags:

r

dplyr

shiny

I have selectInput dropdown like this:

selectInput("locInput", "Location", choices=c("All","New Mexico", "Colorado", "California"))

What I want to achieve is to make selectInput by default not filter by anything, as in when "All" is selected then it should list all observations (so from California, Colorado etc.) So what I tried to do is create simple logic for this:

server <- function(input, output) {
  filtered<-reactive({
    shows %>%
    filter(Length >= input$lenInput[1],
           Length <= input$lenInput[2],
           if (input$locInput != "All"){
           Location==input$locInput
    })

But this doesn't seem to work. Any ideas what can I change in order to make it work correctly?

like image 427
Alex T Avatar asked May 07 '18 16:05

Alex T


2 Answers

There wonderful shinyWidgets package which already has the Select All feature in its pickerInput

library(shiny)
library(shinyWidgets)

ui <- basicPage(
  sidebarPanel(
    pickerInput("locInput","Location", choices=c("New Mexico", "Colorado", "California"), options = list(`actions-box` = TRUE),multiple = T)
  )
)

server <- function(input, output) {

  observe({
    print(input$locInput)
  })

}

shinyApp (ui = ui, server = server)

enter image description here

like image 171
Pork Chop Avatar answered Nov 20 '22 11:11

Pork Chop


You need an else condition. Surprisingly, this works if the condition is TRUE, but if it is FALSE, then filter has an error since you have an empty condition. To solve this, just add else TRUE, which will filter no rows (since TRUE is TRUE for all rows):

data(iris)
iris %>% filter(Petal.Length > 6.4,
                if (FALSE) Sepal.Length > 7.7 else TRUE)
  Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
1          7.6         3.0          6.6         2.1 virginica
2          7.7         3.8          6.7         2.2 virginica
3          7.7         2.6          6.9         2.3 virginica
4          7.7         2.8          6.7         2.0 virginica

iris %>% filter(Petal.Length > 6.4,
                if (TRUE) Sepal.Length > 7.6 else TRUE)
  Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
1          7.7         3.8          6.7         2.2 virginica
2          7.7         2.6          6.9         2.3 virginica
3          7.7         2.8          6.7         2.0 virginica
like image 5
divibisan Avatar answered Nov 20 '22 11:11

divibisan