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

使用texreg导出fixest包feols固定效应模型时出错求助

解决fixest+texreg导出固定效应模型时的GOF长度不匹配错误

问题场景

使用fixest包的feols估计带固定效应的模型后,调用texreg导出结果时出现如下错误:

library(fixest)
library(texreg)

race <- sample(c(0,1), replace=TRUE, size=100)
sex <- sample(c(0,1), replace=TRUE, size=100)
stranger <- sample(c(0,1), replace=TRUE, size=100)
dat <- data.frame(cbind(race, sex, stranger))

# 添加固定效应时出错
model1 <- feols(stranger ~ race|sex, data=dat)
texreg(model1)
# Error in validityMethod(object) : 
#   gof.names and gof must have the same length!

错误根源在于texreg提取拟合优度(GOF)时,R²和调整R²的计算出现了长度不匹配问题。

可行修复方法

方法1:调用texreg时排除R²和调整R²

直接在texreg函数中指定不包含R²和调整R²,避免触发长度不匹配的校验:

texreg(model1, include.rsquared = FALSE, include.adjrs = FALSE)

执行后即可正常导出模型系数与样本量、固定效应组数等信息。

方法2:自定义feols模型的extract方法

重新定义texreg针对feols对象的提取方法,确保拟合优度的名称和数值长度一致:

setMethod("extract", signature = className("feols", "fixest"), definition = function(model, include.rsquared = TRUE, include.adjrs = TRUE, ...) {
  s <- summary(model)
  coef <- s$coefficients[, 1]
  se <- s$coefficients[, 2]
  pval <- s$coefficients[, 4]
  gof <- numeric()
  gof.names <- character()
  gof.decimal <- logical()
  
  # 添加样本量
  gof <- c(gof, nobs(model))
  gof.names <- c(gof.names, "Num. obs.")
  gof.decimal <- c(gof.decimal, FALSE)
  
  # 添加固定效应组数信息
  fe_info <- model$fixef_info
  for (i in seq_along(fe_info)) {
    gof <- c(gof, fe_info[[i]]$n)
    gof.names <- c(gof.names, paste0("Num. groups: ", names(fe_info)[i]))
    gof.decimal <- c(gof.decimal, FALSE)
  }
  
  # 仅在R²有效时添加到GOF
  if (include.rsquared && !is.na(s$r2)) {
    gof <- c(gof, s$r2)
    gof.names <- c(gof.names, "R²")
    gof.decimal <- c(gof.decimal, TRUE)
  }
  # 仅在调整R²有效时添加到GOF
  if (include.adjrs && !is.na(s$adj_r2)) {
    gof <- c(gof, s$adj_r2)
    gof.names <- c(gof.names, "Adj. R²")
    gof.decimal <- c(gof.decimal, TRUE)
  }
  
  tr <- createTexreg(
    coef.names = names(coef),
    coef = coef,
    se = se,
    pvalues = pval,
    gof.names = gof.names,
    gof = gof,
    gof.decimal = gof.decimal
  )
  return(tr)
})

定义完成后,直接调用texreg(model1)即可正常导出完整结果,包括有效情况下的R²和调整R²。

方法3:更新依赖包

texreg或fixest的后续版本可能已修复该兼容性问题,执行以下命令更新包后重试:

update.packages(c("texreg", "fixest"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:07:13