Shiny selectInput to select all from dropdown

2020-02-12 04:18发布

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 doesnt seem to work. Any ideas what can I change in order to make it working correctly?

标签: r shiny dplyr
2条回答
▲ chillily
2楼-- · 2020-02-12 05:01

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

查看更多
唯我独甜
3楼-- · 2020-02-12 05:06

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
查看更多
登录 后发表回答