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

Flextable垂直合并后修改单元格值与调整横线格式的实现

实现方案

需求1:填充Problem字段合并后空单元格

最简单的实现方式是先对原始数据集的Problem列做预处理,将缺失值替换为目标值None identified,再执行垂直合并,连续相同值会自动合并为单元格,无需合并后二次修改:

library(dplyr)
library(flextable)

# 预处理原始数据
example <- example %>%
  mutate(Problem = ifelse(is.na(Problem), "None identified", Problem))

如果你不想修改原始数据集,也可以在构建flextable时通过参数指定缺失值展示内容:

ft_example <- example %>%
  flextable() %>%
  colformat_char(j = "Problem", na_str = "None identified")

需求2:调整水平分隔线

可以先移除body部分所有默认的水平分隔线,再按需添加符合要求的两类分隔线即可:

ft_example <- example %>%
  flextable() %>%
  # 执行垂直合并
  merge_v(j = ~ Micro + Paper + Reference + Problem) %>%
  # 移除body部分所有默认水平分隔线
  hline(part = "body", border = fp_border(width = 0)) %>%
  # 保留表头底部分隔线
  hline_bottom(part = "header", border = fp_border(width = 0.5)) %>%
  # 添加Micro/Paper/Reference分组区分线,通用写法无需硬编码行号
  hline(i = cumsum(rle(example$Micro)$lengths), 
        part = "body", border = fp_border(width = 0.5)) %>%
  # 添加Problem不同取值之间的分隔线
  hline(i = which(lag(example$Problem, default = first(example$Problem)) != example$Problem),
        part = "body", border = fp_border(width = 0.5)) %>%
  theme_vanilla()

# 输出到word验证即可
ft_example

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:54:03