如何在etable中显示(多)估计的权重与系数p值
使用
etable()显示权重和p值的解决方案 问题说明
我需要将多个回归估计结果整合到etable()表格中。使用summary()查看单个估计时,能获取系数的p值及所用权重;但使用etable()无论是单个还是多个估计,这两项信息都无法直接看到。我已经知道用fitstat=可以添加N、IVF、R²等统计量,用coefstat=能添加t统计量或置信区间,但不清楚如何显示p值和权重。
示例对比:
执行以下代码时:
summary(feols(y ~ 0 | i + t | x ~ z, weights = ~n, df), vcov = "hetero")
能得到Weights: n以及fit_x的Pr(>|t|);但执行:
etable(feols(y ~ 0 | i + t | x ~ z, weights = ~n, df), vcov = "hetero")
就看不到权重和p值。
可复现数据代码:
i <- c("a","a","a","a","b","b","b","b","c","c","c","c","d","d","d","d") t <- c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4) y <- rnorm(16) x <- rnorm(16) z <- rnorm(16) n <- c(2,2,2,2,1,1,1,1,6,6,6,6,8,8,8,8) df <- data.frame(i,t,y,x,z,n)
解决方法
1. 显示系数p值
直接使用coefstat="pvalue"参数即可让etable()显示每个系数对应的p值,还能通过coefstat_format指定显示格式(比如保留三位小数):
etable(feols(y ~ 0 | i + t | x ~ z, weights = ~n, df), vcov = "hetero", coefstat = "pvalue", coefstat_format = "%.3f")
如果想同时展示系数和p值(比如把p值放在系数后的括号里),可以自定义统计量函数并传给coefstat:
# 自定义函数,返回"系数(p值)"格式的字符串 my_coef_stat <- function(model_stats) { p_val <- pnorm(abs(model_stats$stat), lower.tail = FALSE) * 2 sprintf("%.3f (%.3f)", model_stats$estimate, p_val) } etable(feols(y ~ 0 | i + t | x ~ z, weights = ~n, df), vcov = "hetero", coefstat = my_coef_stat)
2. 显示权重信息
要在表格底部添加权重说明,通过fitstat参数自定义统计量函数,提取模型中的权重变量名:
# 自定义函数,提取模型的权重信息 get_weight_detail <- function(model) { if (!is.null(model$weights)) { paste("Weights:", deparse(model$weights[[2]])) } else { "No weights applied" } } etable(feols(y ~ 0 | i + t | x ~ z, weights = ~n, df), vcov = "hetero", coefstat = "pvalue", coefstat_format = "%.3f", fitstat = list("Weight Info" = get_weight_detail, "Observations" = "nobs", "R²" = "r2"))
多模型整合示例
如果要同时展示多个模型的结果,上述方法同样适用:
# 拟合两个不同模型 model1 <- feols(y ~ 0 | i + t | x ~ z, weights = ~n, df) model2 <- feols(y ~ x | i + t, weights = ~n, df) # 生成包含p值和权重的整合表格 etable(model1, model2, vcov = "hetero", coefstat = "pvalue", coefstat_format = "%.3f", fitstat = list("Weight Info" = get_weight_detail, "Observations" = "nobs"))
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

