Hi,
I need to filter a dataframe based on multiple input values from checkboxGroupInput widgets. I have prepared a Reprex. When filtering based on single selection, is fine but how do I filter based on multiple selection, for example, based on age and hobby. Thank you for your help.
Reprex:
library(shiny)
library(shinyWidgets)
id<-c(1:20)
name<-rep(c("John","Mike","Paul","Thomas","Frank"),4)
age<-rep(c(21:30),2)
hobby<-rep(c("Hockey","Baseball","Swimming","Reading"),5)
zipcode<-rep(c(4800,4801,2025,2024),5)
df<-data.frame(id,name,age,hobby,zipcode)
head(df)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Reprex App"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
actionButton("update.filter", "Update"),
br(),
br(),
checkboxGroupInput("filter.options","Filters",choices = c("name","age","hobby","zipcode"),
selected ="age" ),
sliderInput("age.user", label = h3("Age"), min = 21, max=30,value = 25),
radioButtons("hobby.user", label = h3("Hobby"),
choices = list("Hockey" = "Hockey",
"Baseball" = "Baseball",
"Swimming" = "Swimming",
"Reading"="Reading"),
selected = "Reading"),
textInput("name.user", label = h3("Name"), value = "Type a name"),
pickerInput(inputId = 'zip.user',
label = 'Zip selection',
choices = unique(df$zipcode),
options = list(`style` = "btn-info"))
),
# Show a filtered table
mainPanel(
h2("Table 1"),
DT::dataTableOutput("table.1"),
)
)
)
server <- function(input, output) {
dfx<-eventReactive(input$update.filter,{
if(input$filter.options=="age") {
df[df$age == input$age.user, ]
} else if(input$filter.options=="name"){
df[df$name == input$name.user, ]
} else if(input$filter.options=="hobby"){
df[df$hobby == input$hobby.user, ]
} else if(input$filter.options=="zipcode"){
df[df$zipcode == input$zip.user, ]
}
})
observeEvent(input$filter_options,
{
message(input$filter_options)
})
observeEvent(input$age.user,
{
message(input$age.user)
})
observeEvent(input$name.user,
{
message(input$name.user)
})
output$table.1 = DT::renderDataTable(
dfx()
,options = list(searching = FALSE, scrollX=TRUE,pageLength = 20))
}
# Run the application
shinyApp(ui = ui, server = server)