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

如何从R对象提取F检验结果并自动导入modelsummary回归汇总表

解决方案

car::linearHypothesis()返回的结果为结构化数据框,可直接提取所需的F统计量、p值,再传入modelsummary的add_rows或gof_map参数自动插入汇总表,无需手动录入。以下是可直接复用的实现代码:


步骤1:拟合模型与执行F检验

library(modelsummary)
library(car)
library(dplyr)

# 示例:拟合6个回归模型(可替换为你自己的模型对象)
data("Mroz")
mod1 <- lm(lwg ~ age + kidslt6, data = Mroz)
mod2 <- lm(lwg ~ age + kidslt6 + kidsge6, data = Mroz)
mod3 <- lm(lwg ~ age + kidslt6 + kidsge6 + educ + exper, data = Mroz)
mod4 <- lm(lwg ~ age + kidslt6, data = subset(Mroz, hours>0))
mod5 <- lm(lwg ~ age + kidslt6 + kidsge6, data = subset(Mroz, hours>0))
mod6 <- lm(lwg ~ age + kidslt6 + kidsge6 + educ + exper, data = subset(Mroz, hours>0))

# 执行educ、exper的联合显著性F检验
F3 <- linearHypothesis(mod3, hypothesis = c("educ = 0", "exper = 0"))
F6 <- linearHypothesis(mod6, hypothesis = c("educ = 0", "exper = 0"))

步骤2:自动提取检验结果并生成显著性星号

# 自定义显著性星号规则(可根据需求调整阈值)
get_sig_stars <- function(p_value) {
  case_when(
    p_value < 0.001 ~ "***",
    p_value < 0.01 ~ "**",
    p_value < 0.05 ~ "*",
    p_value < 0.1 ~ "+",
    TRUE ~ ""
  )
}

# 从F检验结果对象提取所需值
## 提取F统计量,保留2位小数+拼接显著性星号
f3_output <- paste0(round(F3$F[2], 2), get_sig_stars(F3$`Pr(>F)`[2]))
f6_output <- paste0(round(F6$F[2], 2), get_sig_stars(F6$`Pr(>F)`[2]))
## 提取p值,小于0.001时特殊格式化
p3_output <- ifelse(F3$`Pr(>F)`[2] < 0.001, "<0.001", round(F3$`Pr(>F)`[2], 3))
p6_output <- ifelse(F6$`Pr(>F)`[2] < 0.001, "<0.001", round(F6$`Pr(>F)`[2], 3))

步骤3:构造新增行传入modelsummary生成表格

# 构造add_rows数据框:第一列为行标签,后续列依次对应6个模型的结果,无结果的位置填空字符串
custom_rows <- data.frame(
  term = c("educ+exper 联合F值", "educ+exper 联合p值"),
  `模型1` = c("", ""),
  `模型2` = c("", ""),
  `模型3` = c(f3_output, p3_output),
  `模型4` = c("", ""),
  `模型5` = c("", ""),
  `模型6` = c(f6_output, p6_output),
  check.names = FALSE
)

# 可选:指定新增行放在拟合优度区域上方
attr(custom_rows, "position") <- 100

# 生成最终汇总表
modelsummary(
  models = list(mod1, mod2, mod3, mod4, mod5, mod6),
  add_rows = custom_rows,
  stars = c("*" = 0.05, "**" = 0.01, "***" = 0.001) # 与自定义星号规则保持一致即可
)

如果需要把F检验结果整合到拟合优度(GOF)模块,只需将提取到的统计量塞入对应模型的glance结果,再通过gof_map参数配置展示规则即可,逻辑与上述提取流程完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:09:03