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

如何在crosstalk复选框过滤器旁显示匹配条目数量?

在crosstalk复选框过滤器旁显示匹配条目数量

我正在使用crosstalk的复选框过滤器对reactable制作的表格条目进行过滤,需要一种简便方法让复选框旁显示对应匹配条目的数量。以下是带复选框过滤器的表格最简示例:

Example.Rmd

---
title: "Filtering with crosstalk"
---

```{r}
library(reactable)
library(crosstalk)

data <- SharedData$new(iris)

filter_checkbox("species", "Species", data, ~Species)

reactable(data)
当前效果:复选框仅显示物种名称,无对应条目数量。
目标效果:复选框旁显示对应物种的条目数量(格式如 `setosa (50)`)。

---

## 最简单实现方法

### 静态显示数量(无需联动更新)
如果不需要在其他过滤器联动时动态刷新数量,直接预计算每个类别的条目数,修改`filter_checkbox`的`choices`参数即可:

```r
---
title: "Filtering with crosstalk"
---

```{r}
library(reactable)
library(crosstalk)
library(dplyr)

# 预计算每个物种的条目数,生成"名称(数量)"格式的标签向量
species_labels <- iris %>%
  count(Species) %>%
  mutate(label = paste(Species, paste0("(", n, ")"))) %>%
  select(Species, label) %>%
  tibble::deframe()

data <- SharedData$new(iris)

# 传入自定义choices,值保留原物种名,显示标签为带数量的文本
filter_checkbox("species", "Species", data, ~Species, choices = species_labels)

reactable(data)
### 动态更新数量(支持联动过滤)
如果需要在其他过滤器(如范围过滤器)生效后实时更新数量,结合JavaScript监听crosstalk的过滤事件:

```r
---
title: "Filtering with crosstalk"
---

```{r}
library(reactable)
library(crosstalk)

data <- SharedData$new(iris)

# 给过滤器添加id,方便JS定位
filter_checkbox("species", "Species", data, ~Species, id = "species-filter")

reactable(data)
document.addEventListener('DOMContentLoaded', function() {
  // 获取crosstalk数据组
  const filterEl = document.getElementById('species-filter');
  const groupName = filterEl.dataset.crosstalkGroup;
  const sharedData = window.crosstalkGroups[groupName];

  // 定义更新复选框数量的函数
  function updateCounts() {
    const filteredRows = sharedData.data();
    // 统计当前过滤后每个物种的数量
    const countMap = filteredRows.reduce((acc, row) => {
      acc[row.Species] = (acc[row.Species] || 0) + 1;
      return acc;
    }, {});

    // 更新所有复选框标签
    document.querySelectorAll('#species-filter .checkbox label').forEach(label => {
      const species = label.textContent.trim();
      label.textContent = `${species} (${countMap[species] || 0})`;
    });
  }

  // 初始加载和过滤事件触发时更新
  updateCounts();
  sharedData.on('filter', updateCounts);
});
---

内容的提问来源于stack exchange,提问作者Ulrik Lyngs
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:10:35