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

如何在gt包表格的跨列标题间添加贯穿全表的粗竖线

在gt包表格中为跨列标题添加贯穿表格的粗竖线

gt包默认没有直接配置跨列标题间贯穿竖线的选项,我们可以通过tab_style()结合cell_borders(),给对应列组的边界列设置粗边框,同时覆盖表头和数据行,实现竖线贯穿整个表格的效果。

完整实现代码

library(gt)
library(dplyr)

gtcars %>%
  dplyr::select(
    -mfr, -trim, bdy_style, drivetrain,
    -drivetrain, -trsmn, -ctry_origin
  ) %>%
  dplyr::slice(1:8) %>%
  gt(rowname_col = "model") %>%
  tab_spanner(
    label = "performance",
    columns = c(
      hp, hp_rpm, trq, trq_rpm,
      mpg_c, mpg_h
    )
  ) %>%
  # year列右侧添加2px竖线(覆盖表头和数据行)
  tab_style(
    style = cell_borders(
      side = "right",
      weight = px(2),
      color = "black"
    ),
    locations = list(
      cells_column_labels(columns = year),
      cells_body(columns = year)
    )
  ) %>%
  # bdy_style列右侧添加2px竖线
  tab_style(
    style = cell_borders(
      side = "right",
      weight = px(2),
      color = "black"
    ),
    locations = list(
      cells_column_labels(columns = bdy_style),
      cells_body(columns = bdy_style)
    )
  ) %>%
  # performance组左侧(hp列)添加2px竖线
  tab_style(
    style = cell_borders(
      side = "left",
      weight = px(2),
      color = "black"
    ),
    locations = list(
      cells_column_labels(columns = hp),
      cells_body(columns = hp)
    )
  ) %>%
  # performance组右侧(mpg_h列)添加2px竖线
  tab_style(
    style = cell_borders(
      side = "right",
      weight = px(2),
      color = "black"
    ),
    locations = list(
      cells_column_labels(columns = mpg_h),
      cells_body(columns = mpg_h)
    )
  ) %>%
  # msrp列左侧添加2px竖线
  tab_style(
    style = cell_borders(
      side = "left",
      weight = px(2),
      color = "black"
    ),
    locations = list(
      cells_column_labels(columns = msrp),
      cells_body(columns = msrp)
    )
  )

关键说明

  • 核心逻辑是给每个列组的边界列设置粗边框,同时将样式应用到cells_column_labels()(表头)和cells_body()(数据行),确保竖线贯穿整个表格。
  • 针对需求,我们分别给year右侧、bdy_style右侧、performance组的左右两侧、msrp左侧添加了2px粗的黑色竖线,精准分隔各个跨列标题区域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:10:24