R:如何(不)在 shinydashboard 中过滤

R: how (not to) filter in shinydashboard

这是一个非常简单的闪亮仪表板:

# Load libraries
library(shiny)
library(shinydashboard)
library(tidyverse)

data <- data.frame(sex = sample(c("Male", "Female"), size=100, replace=TRUE),
                   smoker = sample(c("yes", "no"), size=100, replace=TRUE))

## UI ##
ui <- dashboardPage(
    dashboardHeader(
        title = "My Dashboard"
    ),
    dashboardSidebar(
        sidebarMenu(
            
        )
        
    ),
    dashboardBody(
        box(
            title="Barplot", status='primary', solidHeader = T,
            plotOutput("myBarplot")
        ),
        box(
            title="Filter", status='warning', solidHeader = T,
            selectInput("findSex", "Choose sex:", c("All", "Male", "Female"))
        )              
    )
)
    
        

## Server ##
server <- function(input, output){
    set.seed(122)
    
    filtered_df <- reactive({
        data <- data %>% filter(sex == input$findSex)
        data})
    
    output$myBarplot <- renderPlot({
        filtered_df() %>% ggplot(aes(x = smoker)) + geom_bar()  + ylab("Prozente")
    })
}

shinyApp(ui, server)

仪表板显示 smokers/non-smokers 的数量,您可以按性别筛选。实现方式如下:

        data <- data %>% filter(sex == input$findSex)

现在我有两个问题:

您可以在 c('Male','Female') 中转换 'All' 并使用 %in% :

  filtered_df <- reactive({
    if (input$findSex == "All") {
       sexSelect <- c('Male','Female')
    }
    else {
       sexSelect <- input$findSex
    }
    data %>% filter(sex %in% sexSelect)
    })