Reputation: 101
I want to filter a data frame such that I only choose rows where a categorical variable contains values chosen by the user of the shiny app.
Here is a reproducible example:
## app.R ##
library(shiny)
library(shinydashboard)
library(tidyverse)
library(DT)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
selectInput("cut", "Type of cut",
c("All",as.character(unique(diamonds$cut))), selected = "All",
multiple = TRUE)
),
dashboardBody(
DT::dataTableOutput("table")
)
)
server <- function(input, output) {
selectdata <- reactive({
diamonds %>%
filter(ifelse(any(input$cut == "All"), cut %in% unique(diamonds$cut),
cut %in% input$cut))
})
output$table <- DT::renderDT({
selectdata()
}, options = list(scrollX = TRUE))
}
shinyApp(ui, server)
The app runs without error, but when a user removes "All" and chooses e.g. "Premuim" and "Good" nothing shows up. However, when a user chooses "Ideal" all of the rows show up. I cannot seem to see what I am doing wrong.
Upvotes: 1
Views: 551
Reputation: 28339
I replaced ifelse
with simple if
condition. I guess this is more safe as piping to filter
and then using ifelse
might get you a bug. Consider this server code:
library(shiny)
server <- function(input, output) {
selectdata <- reactive({
# Give back original data (no filter is needed)
if (any(input$cut == "All")) {
diamonds
} else {
# Subset data
# You can also use: base::subset(diamonds, cut %in% input$cut)
dplyr::filter(diamonds, cut %in% input$cut)
}
})
output$table <- DT::renderDT({
selectdata()
}, options = list(scrollX = TRUE))
}
Upvotes: 1