'Include 'blank' filters in dplyr filter chain in Shiny app
I have a shiny
application with numerous user inputs including numericInput
and textInput
and pickerInput
. These inputs are used to filter a dataframe.
In my filtering chain, however, I need to accept any combination of inputs, even if the user doesn't provide data for a given input. For example, a user may filter using just the numericInput
field, or the textInput
and pickerInput
fields, while submitting no information in the numericInput
field.
What would be the best way of achieving this, on the basis that the total number of user inputs could be n large? In essence, is it possible to keep all inputs in the filtering chain within server
, but ignore those input fields where the user provides no input data?
Example app:
library(dplyr)
library(shiny)
data<-tibble(ref=c("ABC", "ABC", "XYZ", "XYZ", "FGH", "FGH", "FGH"),
type=c("A", "B", "A", "A", "A", "A", "B"),
number=c("1", "17", "54", "23", "6", "87", "3"))
ui <- fluidPage(
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
textInput("text", label = "Type in Ref", value = NULL),
selectInput("select", label = "Select input", choices = c(unique(data$type))),
numericInput("numeric", label = "Type in number", value = NULL)
),
mainPanel(
tableOutput("data")
)
)
)
server <- function(input, output, session) {
filterData = reactiveVal(data)
filtered_df <- reactive({
res <- filterData() %>%
filter(ref == input$text)
res
})
output$data<-renderTable({
filtered_df()
})
}
shinyApp(ui, server)
Expected outputs
If someone filters on ref=='XYZ'
only:
ref type number
XYZ A 54
XYZ A 23
If someone filters on ref=='FGH'
and type=='B'
:
ref type number
FGH B 3
I someone filters on number==54
only:
ref type number
XYZ A 54
Solution 1:[1]
I think the easiest way is to put several if
conditions in reactive()
:
filtered_df <- reactive({
res <- filterData()
if (!is.null(input$text) && input$text != "") {
res <- res %>%
filter(ref == input$text)
}
if (!is.null(input$select)) {
res <- res %>%
filter(type == input$select)
}
if (!is.na(input$numeric)) {
res <- res %>%
filter(number == input$numeric)
}
res
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bretauv |