I created a shiny app and want to implement an "either or" filter.
Let's say everything is preselected, so the table displays completely. If I select one filter, than the other filter is dismissed/ignored/nulled/...
For example I'm selecting 'gears' = 3 and 'carb' is nulled. Than I'm adding 'gears' = 4. After that I'm selecting 'carb' = 1 and the the 'gear' filter is nulled.
Maybe someone can help me with it. I'm wrapping my head around this problem. I think I need to use reactive or eventReactive or some other kind of reactive-expression. But maybe someone here has an idea.
library(shiny)
library(shinyWidgets)
data(mtcars)
allcarbs <- sort(unique(mtcars$carb))
allgears <- sort(unique(mtcars$gear))
ui <- fluidPage(
pickerInput(inputId = "carbinput",
label = h4("carb"),
choices = allcarbs,
selected = allcarbs,
multiple = TRUE, options = list('actions-box' = TRUE)),
h4("or"),
pickerInput(inputId = "gearinput",
label = h4("gears"),
choices = allgears,
selected = allgears,
multiple = TRUE, options = list('actions-box' = TRUE)),
tableOutput("mtcarstab")
)
server <- function(input, output, session) {
output$mtcarstab <- renderTable({
subset(mtcars,
gear %in% as.numeric(input$gearinput) |
carb %in% as.numeric(input$carbinput))
})
}
shinyApp(ui, server)
a simple solution:
before declaring server or UI, create reactive values
vals=reactiveValues(carb=FALSE,gear=FALSE)
then you can use observeEvent to change them on your server:
observeEvent(input$gearinput,{
vals$gear=TRUE
vals$carb=FALSE
})
observeEvent(input$carbinput,{
vals$gear=FALSE
vals$carb=TRUE
})
mytable=eventReactive(c(vals$gear,vals$carb,input$carb,input$gear),{
if(vals$carb){return(subset(mtcars,
carb %in% as.numeric(input$carbinput)))}
else{return(subset(mtcars,
gear %in% as.numeric(input$gearinput)))}
})
output$mtcarstab <- renderTable({
mytable()
})
EDIT: I edited the comments into the answer, to make it 100% correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With