You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny交互式列筛选需求:默认显示全量数据

Shiny交互式数据过滤解决方案(默认显示全量数据)

关键修改点

  • 默认状态返回全量数据:当未选择过滤列或未选择具体值时,直接返回原始数据集
  • 支持多选过滤:将过滤逻辑中的==替换为%in%,适配checkboxGroupInput的多选特性
  • 优化初始体验:给pickerInput设置默认选中列,让第二个选择框默认加载对应列的唯一值

完整修改代码

library(shiny)
library(shinyWidgets)
library(dplyr)
library(DT)
library(ggplot2)

# 模拟数据集(替换为你的实际数据)
d <- mtcars %>% 
  mutate(
    `col 1` = factor(cyl),
    `col 2` = factor(gear),
    `col 3` = factor(am),
    `col 4` = factor(carb)
  )

ui <- fluidPage(
  
  sidebarLayout(
    sidebarPanel(
      
      pickerInput("eda_col", "Select variable",
                  choices = c("col 1", "col 2", "col 3", "col 4"), 
                  selected = "col 1"), # 设置默认选中列
      uiOutput("varselect"),
      actionButton("RefreshPlot", label = "Refresh")
    ),
    
    mainPanel(
      dataTableOutput("datatable1"),
      plotOutput("filteredPlot") # 添加图表输出
    )
  )
)

server <- function(input, output) {
    
    output$varselect <- renderUI({
      req(input$eda_col) # 确保列选择完成后再渲染
      vars <- d[[input$eda_col]]
      checkboxGroupInput("level_choice", "Select factors to include", 
                         choices = unique(vars),
                         selected = unique(vars)) # 默认选中所有值,初始显示全量
    })
    
    filteredData <- reactive({
      # 当未选择列或未选择值时,返回全量数据
      if(is.null(input$eda_col) || is.null(input$level_choice)){
        return(d)
      }
      # 用%in%支持多选过滤
      d %>% filter((!! rlang::sym(input$eda_col)) %in% input$level_choice)
    })
    
    output$datatable1 <- renderDataTable({
      datatable(filteredData())
    })
    
    # 基于过滤后的数据生成图表(示例为分组箱线图,可按需修改)
    output$filteredPlot <- renderPlot({
      req(filteredData())
      ggplot(filteredData(), aes(x = .data[[input$eda_col]], y = mpg)) +
        geom_boxplot(fill = "#2c3e50", color = "#ecf0f1") +
        labs(x = input$eda_col, y = "Miles/(US) gallon") +
        theme_minimal()
    })
  
}

shinyApp(ui, server)

代码说明

  1. 默认状态处理:在filteredData响应式对象中,通过is.null判断选择状态,无有效选择时直接返回全量数据
  2. 多选适配:使用%in%替代==,支持同时选择多个值进行过滤
  3. UI优化:给pickerInput设置默认选中列,checkboxGroupInput默认选中所有值,初始状态直接展示全量数据和对应图表
  4. 图表集成:新增图表输出逻辑,基于过滤后的数据生成可视化内容,可根据需求调整图表类型和参数

内容的提问来源于stack exchange,提问作者Murad Khalilov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 05:33:28