问题
Is there a way to put a filter on a Shiny App, but for Shiny to know that if there is nothing selected to show all the data? For example, using the ggplot2 diamonds data, I've built the following:
library(ggplot2)
library(shiny)
library(dplyr)
diamonds <- diamonds
#Unique cut dropdown
cut <- sort(unique(diamonds$cut))
#Unique color
color <- sort(unique(diamonds$color))
#Unique clarity
clarity <- sort(unique(diamonds$clarity))
#Shiny App
ui <- fluidPage(
titlePanel("diamonds"),
fluidRow(
column(3,
selectizeInput("CutSelect", "Cut", cut, selected = NULL, multiple = TRUE),
br(),
selectInput("ColorSelect", "Color", color),
br(),
selectInput("ClaritySelect", "Clarity", clarity)
),
tableOutput("results")
)
)
server <- function(input, output) {
output$results <- renderTable({
filtered <-
diamonds %>%
filter(cut == input$CutSelect,
color == input$ColorSelect,
clarity == input$ClaritySelect)
filtered
})
}
shinyApp(ui = ui, server = server)
Which produces an app that looks like this:
Without cleaning the data, is there a way to add an "All" operator to the filters that will allow the app to know that even though there is a filter for that dimension, that there are instances where "All" would come in handy?
For cut, specifically, if I leave the selectizeInput blank, I'd like that to operate as an "All" or "no filter" type deal.
Happy to provide any more information that can be useful.
Thanks.
回答1:
I would suggest using the DT when it comes to presenting/filtering data. DT has a builtin filter option, which allows you to filter one or several values or range of values in the table. You may put the filter at the top or bottom of the table. Here is the code which meets your objectives:
library(ggplot2)
library(shiny)
library(DT)
diamonds <- diamonds
#Shiny App
ui <- fluidPage(
titlePanel("diamonds"),
fluidRow(
dataTableOutput("results")
)
)
server <- function(input, output) {
output$results <- DT::renderDataTable(filter='top',{
diamonds
})
}
shinyApp(ui = ui, server = server)
回答2:
An empty selectInput returns NULL so you could do the filtering only if the selectInput is not NULL (i.e. one or more values have been selected):
server <- function(input, output) {
output$results <- renderTable({
filtered <- diamonds
if (!is.null(input$CutSelect)) {
filtered <- filtered %>% filter(cut == input$CutSelect)
}
if (!is.null(input$ColorSelect)) {
filtered <- filtered %>% filter(color == input$ColorSelect)
}
if (!is.null(input$ClaritySelect)) {
filtered <- filtered %>% filter(clarity == input$ClaritySelect)
}
filtered
})
}
That way if a selectInput is empty (NULL) no filtering is performed on that dimension.
来源:https://stackoverflow.com/questions/42742788/r-shiny-filter-for-all-values