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

基于内容字符串检测为gt表格单元格设置样式遇阻

问题解答:gt包中根据单元格内容设置样式失效的解决办法

问题原因

rows = contains('bad')是gt中用于匹配**行名称(或行索引)**的选择器,而非判断单元格内容。你的数据行名默认是1、2、3,没有包含'bad'的行名,所以样式无法匹配到目标单元格。

解决方案

要根据单元格内容设置样式,需要在rows参数中使用逻辑条件来筛选目标行,这里有两种简洁的实现方式:

方法1:使用where()函数批量处理目标列

通过where()对指定列(starts_with('outcome_'))逐个判断内容是否为'bad',自动匹配所有符合条件的单元格:

library(gt)
library(tibble)

my_data <- tibble(person = c('pablo','spots','harry'), 
                  outcome_1 = c('good','bad','good'),
                  outcome_2 = c('good','good','bad'))

my_data |>
  gt() |>
  tab_style(
    style = list(
      cell_fill(color = 'red'),
      cell_text(weight = 'bold')
    ),
    locations = cells_body(
      columns = starts_with('outcome_'),
      rows = where(function(x) x == 'bad')
    )
  )

方法2:针对单列单独设置逻辑条件

如果需要更精细的控制,可以针对每一列单独指定行筛选条件:

my_data |>
  gt() |>
  # 处理outcome_1列的'bad'单元格
  tab_style(
    style = list(
      cell_fill(color = 'red'),
      cell_text(weight = 'bold')
    ),
    locations = cells_body(
      columns = outcome_1,
      rows = outcome_1 == 'bad'
    )
  ) |>
  # 处理outcome_2列的'bad'单元格
  tab_style(
    style = list(
      cell_fill(color = 'red'),
      cell_text(weight = 'bold')
    ),
    locations = cells_body(
      columns = outcome_2,
      rows = outcome_2 == 'bad'
    )
  )

说明

方法1更适合批量处理同规则的多列,where()函数会遍历columns参数指定的每一列,返回该列中值为'bad'的行位置,从而准确应用样式到目标单元格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:20:12