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

modelsummary包宽表同时展示非标准化与标准化系数及相关问题

使用modelsummary同时展示标准化/非标准化系数并自定义格式的解决方案

以下是针对需求的完整解决方案,包含同时展示两种系数、p值加星号、分列设置小数位数的实现:

修改后的完整代码

library(modelsummary)
library(kableExtra)

# 拟合两个模型
models <- list(
  "Model X" = lm(mpg ~ hp + factor(cyl), data = mtcars),
  "Model Y" = lm(mpg ~ hp + factor(cyl) + qsec, data = mtcars)
)

# 生成原始系数表(包含非标准化系数、SE、t值、p值)
tab_raw <- modelsummary(
  models,
  output = "dataframe",
  statistic = c("std.error", "statistic", "p.value"),
  estimate = "{estimate} ({std.error})",
  stars = TRUE,
  fmt = list(
    "estimate" = 2,
    "std.error" = 2,
    "statistic" = 2,
    "p.value" = 3
  ),
  gof_omit = 'AIC|BIC|Log.Lik.|RMSE'
)

# 生成标准化系数表(包含标准化系数、SE、t值、p值)
tab_std <- modelsummary(
  models,
  output = "dataframe",
  standardize = "basic",
  statistic = c("std.error", "statistic", "p.value"),
  estimate = "{estimate} ({std.error})",
  stars = TRUE,
  fmt = list(
    "estimate" = 2,
    "std.error" = 2,
    "statistic" = 2,
    "p.value" = 3
  ),
  gof_omit = 'AIC|BIC|Log.Lik.|RMSE'
)

# 提取并重命名列,区分原始和标准化结果
raw_cols <- tab_raw[, grepl("Model X|Model Y", colnames(tab_raw))]
std_cols <- tab_std[, grepl("Model X|Model Y", colnames(tab_std))]

colnames(raw_cols) <- c(
  "Raw Est. (SE)", "t", "p",
  "Raw Est. (SE)", "t", "p"
)

colnames(std_cols) <- c(
  "Std. Est. (SE)", "t", "p",
  "Std. Est. (SE)", "t", "p"
)

# 合并表格并设置列标题层级
tab_combined <- cbind(tab_raw[, "term"], raw_cols, std_cols)

test <- tab_combined %>%
  kable(
    col.names = c(
      "",
      "Raw Est. (SE)", "t", "p",
      "Raw Est. (SE)", "t", "p",
      "Std. Est. (SE)", "t", "p",
      "Std. Est. (SE)", "t", "p"
    )
  ) %>%
  kable_styling(font_size = 8) %>%
  row_spec(0, italic = TRUE) %>%
  add_header_above(c(
    " " = 1,
    "Model X" = 3,
    "Model Y" = 3,
    "Model X (Standardized)" = 3,
    "Model Y (Standardized)" = 3
  )) %>%
  add_footnote("Note: Model Y includes control variables", notation = "none")

test

关键问题解决说明

1. 同时展示非标准化和标准化系数

  • 避免直接使用standardize="basic"(该参数会替换原始系数为标准化系数),而是分别生成原始系数表和标准化系数表,再通过列合并的方式将两者整合到同一个表格中。
  • 用output="dataframe"输出数据框格式,方便后续的列操作和合并。

2. 在p值后添加显著性星号

  • 在statistic参数中自定义p值的格式为"{p.value}{stars}",结合stars=TRUE,程序会自动根据显著性水平(*p<0.1, **p<0.05, ***p<0.01)添加对应的星号到p值后方。

3. 分列设置小数位数

  • 使用fmt参数的列表格式,为不同统计量指定小数位数:
    • 非标准化/标准化系数、SE、t值保留2位小数
    • p值单独设置为保留3位小数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:19:01