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

如何在texreg调用中自定义plm面板模型的拟合优度(gof)信息?

解决texreg输出plm模型自定义拟合优度的问题

要实现你想要的自定义拟合优度输出,我们可以利用texreg的custom.gof、custom.gof.names等参数,配合从plm模型对象中提取所需统计量来完成。以下是完整的实现代码:

# 安装并加载包
# install.packages(c("wooldridge", "plm", "texreg"), dependencies = TRUE)
library(wooldridge)
data(wagepan)
library(plm)
library(texreg)

# 拟合模型
POLS <- plm(lwage ~ educ + black + hisp + exper+I(exper^2)+ married + union + factor(year), 
            data = wagepan, index=c("nr","year") , model="pooling")
RE <- plm(lwage ~ educ + black + hisp + exper + I(exper^2) + married + union + factor(year), 
          data = wagepan, index = c("nr","year") , model = "random")
FE <- plm(lwage ~ I(exper^2) + married + union + factor(year), 
          data = wagepan, index = c("nr","year"), model="within")

# 提取自定义拟合优度所需的统计量
# 总观测数
obs_count <- sapply(list(POLS, RE, FE), nobs)
# 个体数量
indiv_count <- sapply(list(POLS, RE, FE), function(x) pdim(x)$nT$n)
# 时间维度长度
time_length <- sapply(list(POLS, RE, FE), function(x) pdim(x)$nT$T)
# F/Wald统计量(POLS和FE用F检验,RE用Wald检验)
stat_value <- c(summary(POLS)$fstatistic[1], 
                summary(RE)$waldstatistic[1], 
                summary(FE)$fstatistic[1])
# 对应的P值
p_value <- c(summary(POLS)$fstatistic[4], 
             summary(RE)$waldstatistic[3], 
             summary(FE)$fstatistic[4])

# 调用screenreg生成自定义输出
screenreg(list(POLS, RE, FE), 
          custom.coef.map = list('married' = 'Married', 'union' = 'Union'),
          include.nobs = FALSE,  # 关闭默认的Num. obs.输出
          include.r2 = TRUE,     # 保留R²
          include.adjr2 = TRUE,  # 保留调整后R²
          custom.gof = list(obs_count, indiv_count, time_length, stat_value, p_value),
          custom.gof.names = c("Obs. (N)", "Indiv.(n)", "Time (T)", "F-stat", "P-value"),
          custom.gof.format = list("%.0f", "%.0f", "%.0f", "%.4f", "(%.2e)")  # 设置每个统计量的输出格式
)

代码解释:

  1. 统计量提取:

    • 用sapply批量处理三个模型,避免重复代码;
    • pdim()函数是plm包专门用于提取面板数据维度的工具,能直接拿到个体数n和时间维度T;
    • 注意随机效应(RE)模型默认使用Wald检验而非F检验,所以我们提取的是waldstatistic,和POLS/FE的fstatistic对应。
  2. texreg参数配置:

    • include.nobs = FALSE:关闭默认的Num. obs.输出,换成我们自定义的Obs. (N);
    • custom.gof:传入我们提取的所有自定义统计量,每个元素对应一行输出;
    • custom.gof.names:给每一行自定义统计量设置显示名称;
    • custom.gof.format:设置每个统计量的输出格式,比如整数用%.0f,小数保留四位用%.4f,P值用科学计数法加括号。

运行上述代码后,就能得到你期望的包含个体数、时间维度、F/Wald统计量及P值的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:09:31