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

如何用R的purrr包自动化实现gt包多列多颜色格式设置

用{purrr}自动化{gt}报表的多列区间填充色设置

日常使用{gt}制作报表时,需为多列数据按不同分数区间设置填充色,手动重复调用tab_style效率极低,可借助{purrr}包实现自动化操作。

示例数据集

library(tibble)
library(gt)
library(purrr)

data_tbl <- tibble(
  name = c('deng', 'alier',  'atem', 'garang', 'akuien'), 
  english = c(87, 57, 76, 98, 79), 
  mathematics = c(88, 98, 87, 69, 88), 
  statistics = c(76, 99, 58,  84,  90)
)

自动化解决方案

1. 定义样式规则

把分数区间与对应填充色整理成规则列表,方便统一管理和修改:

color_rules <- list(
  list(condition = ~ .x >= 80, color = "#1dab48"),   # 绿色:80分及以上
  list(condition = ~ .x >= 70 & .x < 80, color = "#c97928"), # 黄色:70-79分
  list(condition = ~ .x < 70, color = "#c94e28")    # 红色:70分以下
)

2. 指定需要处理的列

自动筛选出除name外的数值列,无需手动列举:

cols_to_style <- setdiff(names(data_tbl), "name")

3. 用{purrr}批量应用样式

通过两层reduce函数,遍历所有列和样式规则,自动叠加表格样式:

my_gt_auto <- data_tbl %>%
  gt() %>%
  reduce(
    .x = cols_to_style,
    .f = function(table, col) {
      reduce(
        .x = color_rules,
        .f = function(tbl, rule) {
          tbl %>%
            tab_style(
              style = cell_fill(color = rule$color),
              locations = cells_body(
                columns = all_of(col),
                rows = eval(rule$condition, data_tbl)
              )
            )
        },
        .init = table
      )
    },
    .init = .
  )

# 查看结果
my_gt_auto

代码说明

  • color_rules集中管理区间条件和颜色,后续调整规则只需修改此列表,无需改动核心逻辑。
  • cols_to_style自动识别目标列,新增列时无需手动更新代码,扩展性更强。
  • 两层reduce替代了重复的tab_style调用,大幅减少代码冗余,提升效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:01:09