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

如何在R的texreg生成的LaTeX表格中添加自定义行

在texreg生成的LaTeX表格中间插入空行和副标题的两种方法

texreg本身没有内置参数直接在系数列表中间插入行,但可以通过以下两种方式实现你的需求:

方法1:直接修改texreg输出的LaTeX代码

先让texreg生成基础的LaTeX代码,定位到前4个系数之后的位置,手动插入空行和副标题行。

示例代码:

library(texreg)

# 示例回归模型(替换为你的真实回归结果)
model1 <- lm(mpg ~ cyl + disp + hp + drat + wt + qsec, data = mtcars)
model2 <- lm(mpg ~ cyl + disp + hp + drat + wt + qsec + vs, data = mtcars)

# 用custom.coef.map筛选并排序目标系数(对应你的系数1-4)
coef_map <- list(
  cyl = "系数1",
  disp = "系数2",
  hp = "系数3",
  drat = "系数4",
  wt = "系数5",
  qsec = "系数6",
  vs = "系数7"
)

# 生成LaTeX代码并转为字符向量
tex_code <- capture.output(texreg(list(model1, model2), custom.coef.map = coef_map, return.string = TRUE))

# 先打印查看行号,找到系数4所在行的下一行位置
# print(tex_code)
insert_pos <- which(grepl("系数4", tex_code)) + 1

# 插入空行、副标题和分隔线(可按需调整格式)
new_tex_code <- c(
  tex_code[1:insert_pos],
  "  \\hline",
  "  \\multicolumn{3}{c}{\\textbf{\\textit{Subtitle for Coefficients Below}}} \\\\",
  "  \\hline",
  tex_code[(insert_pos + 1):length(tex_code)]
)

# 输出修改后的LaTeX代码
cat(new_tex_code, sep = "\n")

方法2:用“假系数”模拟副标题

利用custom.coef.map和custom.coef.values插入一个无数值的副标题行,伪装成标题而非系数:

# 沿用上面的示例模型
# 定义包含副标题的系数映射,把副标题放在系数4之后
coef_map_with_title <- list(
  cyl = "系数1",
  disp = "系数2",
  hp = "系数3",
  drat = "系数4",
  subtitle = "\\textbf{\\textit{Subtitle for Coefficients Below}}",
  wt = "系数5",
  qsec = "系数6",
  vs = "系数7"
)

# 给假系数赋值NA,让texreg显示为空
custom_values <- c(
  # model1的系数值
  cyl = coef(model1)["cyl"], disp = coef(model1)["disp"], hp = coef(model1)["hp"], drat = coef(model1)["drat"],
  subtitle = NA, wt = coef(model1)["wt"], qsec = coef(model1)["qsec"], vs = ifelse("vs" %in% names(coef(model1)), coef(model1)["vs"], NA),
  # model2的系数值
  cyl = coef(model2)["cyl"], disp = coef(model2)["disp"], hp = coef(model2)["hp"], drat = coef(model2)["drat"],
  subtitle = NA, wt = coef(model2)["wt"], qsec = coef(model2)["qsec"], vs = coef(model2)["vs"]
)

# 生成表格,设置NA显示为空
texreg(
  list(model1, model2),
  custom.coef.map = coef_map_with_title,
  custom.coef.values = custom_values,
  na.string = "",
  booktabs = TRUE  # 可选,用booktabs格式更美观
)

如果需要空行,可以在副标题前后额外添加假系数行,同样赋值NA并设置na.string = ""即可实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:57:50