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

如何在R Markdown中生成带中间分区表头的PDF格式表格

你正在使用的kableExtra包本身就可以实现该需求,也可以选择flextable包用更直观的逻辑完成配置,两种方案如下:

方案1:基于kableExtra实现

首先识别数据中的分组表头行(即Section/topic列包含粗体格式的行),再通过行级别配置去掉分组行的竖线、保留其余行的竖线:

library(tidyverse)
library(kableExtra)

pc = structure(list(`Section/topic` = c("\\textbf{Title}", "Title", 
"\\textbf{Abstract}", "Structured summary"), `Item No` = c("", 
"1", "", "2"), `Checklist item` = c("", "Identify the report as a systematic review, meta-analysis, or both", 
"", "Provide a structured summary including, as applicable, background, objectives, data sources, study eligibility criteria, participants, interventions, "
), `Reported on page No` = c("", "", "", "")), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

# 识别分组表头行的索引
group_row_idx <- which(grepl("\\\\textbf", pc$`Section/topic`))

pc %>%
  kbl(
    longtable = T, 
    escape = F,
    # 关闭booktabs默认的无竖线规则
    booktabs = F,
    # 定义列格式,默认所有行带竖线
    align = "|p{8em}|p{3em}|p{20em}|p{6em}|"
  ) %>%
  # 针对分组表头行配置:跨列合并、去掉竖线、上下加横线
  row_spec(
    group_row_idx,
    extra_latex_before = "\\hline",
    extra_latex_after = "\\hline",
    extra_latex = paste0("\\multicolumn{4}{@{}l@{}}", pc$`Section/topic`[group_row_idx], "}")
  ) %>%
  kable_styling(latex_options = c("repeat"))

方案2:基于flextable实现

如果不想写LaTeX语法,可以用flextable包,通过可视化配置逻辑实现效果,对PDF输出的兼容性也很好:

library(tidyverse)
library(flextable)
library(officer)

# 识别分组表头行的索引
group_row_idx <- which(grepl("\\\\textbf", pc$`Section/topic`))

pc %>%
  flextable() %>%
  # 设置列宽(单位为英寸)
  width(j = 1, width = 8/2.54) %>%
  width(j = 2, width = 3/2.54) %>%
  width(j = 3, width = 20/2.54) %>%
  width(j = 4, width = 6/2.54) %>%
  # 全局添加竖线
  vline(border = fp_border(width = 0.5), part = "all") %>%
  # 删除分组行的所有竖线
  vline(i = group_row_idx, j = 1:4, border = fp_border(width = 0), part = "body") %>%
  # 分组行上下添加横线
  hline(i = group_row_idx, border = fp_border(width = 0.5), part = "body") %>%
  hline(i = group_row_idx - 1, border = fp_border(width = 0.5), part = "body") %>%
  # 合并分组行的所有列
  merge_h(i = group_row_idx, part = "body") %>%
  # 适配PDF输出
  set_table_properties(layout = "autofit")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:48:00