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

如何基于数据框在flextable中创建指定表头的表格?

生成指定结构的flextable表格

根据你提供的数据,以下是生成符合要求的分层表头flextable的步骤:

1. 准备数据

首先确认你的实际数据:

tibble2 <- data.frame(
  station_code = c("A","A","A","A","B","B","B","B"),
  species_name = c("Species1", "Species2", "Species3", "Species4", "Species1", "Species2", "Species3", "Species4"),
  days_present = c(10,15,20,25,30,35,20,35),
  percent_days_present = c(50,75,80,90,60,70,25,45))

2. 加载依赖包

需要用到dplyr处理数据,flextable构建表格:

library(dplyr)
library(flextable)

3. 重塑数据为宽表

将长格式数据转换为适合分层表头的宽格式,每个站点对应两个指标列:

wide_data <- tibble2 %>%
  pivot_wider(
    id_cols = species_name,
    names_from = station_code,
    values_from = c(days_present, percent_days_present),
    names_glue = "{station_code}_{.value}"
  )

4. 创建flextable并设置分层表头

构建表格并配置两层表头:第一层为站点名称,第二层为具体指标:

ft <- flextable(wide_data) %>%
  # 设置二级表头标签
  set_header_labels(
    species_name = "物种名称",
    A_days_present = "出现天数",
    A_percent_days_present = "占比(%)",
    B_days_present = "出现天数",
    B_percent_days_present = "占比(%)"
  ) %>%
  # 合并同一站点下的二级表头单元格,生成一级表头
  merge_at(i = 1, j = 2:3, part = "header") %>%
  merge_at(i = 1, j = 4:5, part = "header") %>%
  # 设置一级表头的站点名称
  compose(i = 1, j = 2, value = as_paragraph("站点A"), part = "header") %>%
  compose(i = 1, j = 4, value = as_paragraph("站点B"), part = "header") %>%
  # 统一表头和内容的居中对齐
  align(align = "center", part = "header") %>%
  align(align = "center", part = "body")

5. 查看或导出表格

  • 在RStudio中直接输入ft即可预览表格
  • 如需导出为Word文档,使用:
save_as_docx(ft, path = "species_station_table.docx")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:06:32