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

如何从reactable表格提取过滤后数据用于Shiny动态密度图?

解决方法

要获取reactable过滤后的数据集,核心是用reactable::getReactableState()函数提取表格的过滤状态,再用这个状态对原始数据进行子集化。以下是完整的示例代码:

完整示例代码

library(shiny)
library(reactable)
library(ggplot2)

# 生成模拟数据
set.seed(123)
d <- data.frame(
  ID = 1:100,
  Group = sample(c("A", "B", "C"), 100, replace = TRUE),
  Score = rnorm(100, mean = 50, sd = 10)
)

ui <- fluidPage(
  tabsetPanel(
    tabPanel("数据表格", reactableOutput("my_table")),
    tabPanel("密度图", plotOutput("score_density"))
  )
)

server <- function(input, output, session) {
  # 渲染带过滤功能的reactable表格
  output$my_table <- renderReactable({
    reactable(
      d,
      filterable = TRUE,  # 开启全局过滤功能
      columns = list(
        Score = colDef(filterable = TRUE)  # 单独指定Score列可过滤(也可依赖全局设置)
      )
    )
  })
  
  # 渲染基于过滤后数据的密度图
  output$score_density <- renderPlot({
    # 获取reactable的过滤状态:返回逻辑向量,标记未被过滤的行
    filtered_rows <- reactable::getReactableState("my_table", "filtered")
    
    # 提取过滤后的数据集,drop=FALSE确保结果保持dataframe格式
    filted_d <- d[filtered_rows, , drop = FALSE]
    
    # 绘制密度图
    ggplot(filted_d, aes(x = Score)) +
      geom_density(fill = "#2c3e50", alpha = 0.6) +
      labs(title = "Score列密度分布(过滤后)", x = "Score", y = "密度") +
      theme_minimal()
  })
}

shinyApp(ui, server)

关键说明

  • reactable::getReactableState("my_table", "filtered"):第一个参数对应reactable的输出ID,第二个参数指定获取"filtered"状态,返回与原始数据行数匹配的逻辑向量,TRUE代表该行未被过滤。
  • 用d[filtered_rows, , drop = FALSE]避免因过滤后只剩一行导致数据集降级为向量的问题。
  • renderPlot会自动监听getReactableState的返回值变化,调整表格过滤条件时,密度图会自动更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:14:59