Reactively filtering/subsetting a data frame in shiny

倖福魔咒の 提交于 2021-01-29 02:31:16

问题


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.


回答1:


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))
}


来源:https://stackoverflow.com/questions/54840334/reactively-filtering-subsetting-a-data-frame-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!