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

如何为kable()表格添加"Averages"行标签且不破坏格式?

解决方案

要给平均值行左侧添加"Averages"字样,核心是新增一个分类列,仅在最后一行填充文本,同时调整表头的跨列设置。修改后的完整代码如下:

library(tidyverse)
library(kableExtra)

rubric_results <- tibble(
  "Category" = rep("", 9), # 新增分类列,前9行留空
  "PLCO-1" = c(4, 5, 4, 4, 3.5, 3, 5, 4.5, 5),
  "PLCO-2" = c(4, 5, 4, 5, 4, 3, 5, 5, 5),
  "PLCO-3" = c(4, 5, 4, 4, 4, 4, 5, 4, 5),
  "PLCO-4" = c(4.33, 5, 4.33, 3.33, 3.67, 2.67, 5, 4.33, 5),
  "PLCO-5" = c(3.67, 5, 4, 3, 3.67, 3, 5, 4, 4.33)
)

averages <- colMeans(rubric_results[, -1], na.rm = TRUE) # 计算平均值时排除新增的Category列

# 绑定平均值行,给Category列赋值"Averages"
rubric_results <- bind_rows(rubric_results, 
     tibble("Category" = "Averages",
            "PLCO-1" = averages[1], "PLCO-2" = averages[2], 
            "PLCO-3" = averages[3], "PLCO-4" = averages[4], 
            "PLCO-5" = averages[5])) %>%
  mutate(across(-Category, ~round(., 2))) # 仅对数值列保留两位小数

headers = c("Summary of Findings" = 6) # 表头跨列数从5改为6,适配新增列

rubric_results %>%
  kable("latex", booktabs = TRUE, caption = "\\\\vspace{-2mm} \\\\Large Title",
        col.names = c("", names(rubric_results)[-1])) %>% # 隐藏Category列的表头
  kable_styling(latex_options = c("hold_position")) %>%
  add_header_above(headers) %>%
  row_spec(nrow(rubric_results) - 1, hline_after = TRUE) %>%  
  row_spec(nrow(rubric_results), bold = TRUE) 

关键修改点:

  • 新增Category列,前9行设为空字符串,平均值行填充"Averages"
  • 计算列平均值时排除Category列,避免计算错误
  • 调整表头跨列数为6,匹配新的列数
  • 隐藏Category列的表头,让表格结构更简洁
  • 仅对数值列进行小数位保留,避免文本列被误处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:18:29