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

使用modelsummary的rbind堆叠模型时,四面板添加行位置异常问题

问题解决:modelsummary多面板堆叠时add_rows位置异常

问题根源

你遇到的位置偏移问题主要来自两个错误:

  1. 自定义行的列名错误:你在tribble中重复使用~term作为列名,这会导致modelsummary无法正确匹配模型列,进而干扰行的插入位置。
  2. position参数计算错误:当使用shape="rbind"堆叠面板时,每个面板默认包含4行(面板标题+2个系数行+1个gof行),要在系数行下方、gof行上方插入自定义行,需要将position设为每个面板gof行的前一行位置。

修正后的代码

3面板示例(验证修正逻辑)

library(AER)
library(modelsummary)

stacks3 <- list(
  "Panel A: MPG" = list(
    "A" = lm(mpg ~ hp, data = mtcars),
    "B" = lm(mpg ~ hp, data = mtcars)),
  "Panel B: MPG" = list(
    "A" = lm(cyl ~ hp, data = mtcars),
    "B" = lm(cyl ~ hp, data = mtcars)),
  "Panel C: MPG" = list(
    "A" = lm(disp ~ hp, data = mtcars),
    "B" = lm(disp ~ hp, data = mtcars))
)

# 修正列名:第一列为行名(term),后续列对应模型名称A、B
rows3 <- tibble::tribble(
  ~term, ~A, ~B,
  'rowA', '-', '-',
  'rowB', '-', '-',
  'rowC', '-', '-'
)
# 每个面板的插入位置为第4、8、12行(gof行的前一行)
attr(rows3, 'position') <- c(4, 8, 12)

modelsummary(
  stacks3,
  coef_omit = -2,
  fmt = 3,
  add_rows = rows3,
  shape = "rbind",
  gof_map = c("nobs")
)

4面板示例(修复位置偏移)

stacks4 <- list(
  "Panel A: MPG" = list(
    "A" = lm(mpg ~ hp, data = mtcars),
    "B" = lm(mpg ~ hp, data = mtcars)),
  "Panel B: MPG" = list(
    "A" = lm(cyl ~ hp, data = mtcars),
    "B" = lm(cyl ~ hp, data = mtcars)),
  "Panel C: MPG" = list(
    "A" = lm(disp ~ hp, data = mtcars),
    "B" = lm(disp ~ hp, data = mtcars)),
  "Panel D: MPG" = list(
    "A" = lm(disp ~ hp, data = mtcars),
    "B" = lm(disp ~ hp, data = mtcars))
)

# 修正列名
rows4 <- tibble::tribble(
  ~term, ~A, ~B,
  'rowA', '-', '-',
  'rowB', '-', '-',
  'rowC', '-', '-',
  'rowD', '-', '-'
)
# 4个面板的插入位置依次为4、8、12、16
attr(rows4, 'position') <- c(4, 8, 12, 16)

modelsummary(
  stacks4,
  coef_omit = -2,
  fmt = 3,
  add_rows = rows4,
  shape = "rbind",
  gof_map = c("nobs")
)

关键说明

  • 列名必须匹配模型输出的列结构:第一列是行名称(term),后续列对应你定义的模型名称(A、B),不能重复使用term。
  • position的计算逻辑:每个面板占4行,第n个面板的插入位置为4 * n,这样自定义行会刚好插入到该面板的系数行之后、Nobs行之前。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:44:54