如何在R的modelsummary库中让估计值与标准误差同行显示?
在R中用modelsummary实现系数与标准误同行显示(适配fixest对象)
modelsummary可以通过自定义estimate参数并配合statistic = NULL来实现类似stargazer的single.row = T效果,具体操作如下:
- 加载所需包并拟合fixest模型
library(modelsummary) library(fixest) # 示例模型:带固定效应的回归 mod <- feols(mpg ~ hp + wt | cyl, data = mtcars)
- 生成同行显示系数与标准误的表格
核心是在estimate参数中用glue语法把系数估计值和标准误合并成一个字符串,同时设置statistic = NULL避免标准误单独占一行:
modelsummary(mod, estimate = "{estimate} ({std.error})", # 格式:系数(标准误) statistic = NULL, fmt = 2) # 控制小数位数
- 扩展:添加t值或p值
如果需要在同行额外显示t值、p值等统计量,直接修改estimate的格式字符串即可:
modelsummary(mod, estimate = "{estimate} ({std.error}) [t = {statistic}]", # 系数(标准误)[t= t值] statistic = NULL, fmt = 2)
- 多模型场景适配
多个fixest模型也可以用同样的方法实现同行显示:
mod1 <- feols(mpg ~ hp | cyl, data = mtcars) mod2 <- feols(mpg ~ hp + wt + qsec | cyl, data = mtcars) modelsummary(list(mod1, mod2), estimate = "{estimate} ({std.error})", statistic = NULL, fmt = 2)
常见问题说明
你之前修改estimate和statistic未成功,大概率是没有设置statistic = NULL,导致标准误仍然单独生成一行。通过将statistic设为NULL,可以完全关闭单独的统计量行,让所有内容都整合到系数行中。
内容的提问来源于stack exchange,提问作者rabbit1234
相关产品推荐
相关产品推荐

