如何用stargazer调整glm回归系数的输出顺序与命名?
Got it, let's figure out how to fix this stargazer issue for your binomial GLM. The problem with your initial order parameter attempt is likely either a mismatch in the exact coefficient names from your model, or not accounting for the intercept term in the order specification. Here are two reliable solutions:
方案一:先调整数据的因子水平(推荐)
This is the cleanest approach because it modifies the source data to get the coefficient order you want right in the model, so stargazer can just pick it up directly:
- 重新指定
IV的因子水平顺序,匹配你想要的输出顺序:# 重新设定因子水平,顺序就是你最终想展示的顺序 df$IV <- factor(df$IV, levels = c("BBB", "AAA", "DDD", "CCC")) - 重新拟合GLM模型(此时模型的系数顺序会和因子水平顺序一致):
model <- glm(formula = DV ~ IV, family = "binomial", data = df) - 用
stargazer输出,直接用covariate.labels重命名系数:stargazer(model, type = "html", out = "./out/test.html", title = "Title", covariate.labels = c("BBB", "AAA", "DDD", "CCC"))
方案二:直接在Stargazer中调整(无需重新拟合模型)
If you don't want to refit the model, you can fix the order and names directly in stargazer—you just need to make sure you use the exact coefficient names from your model.
首先确认模型中系数的精确名称(这一步至关重要,避免名称匹配错误):
print(names(coef(model)))你会看到类似这样的输出:
"(Intercept)", "as.factor(IV)AAA", "as.factor(IV)BBB", "as.factor(IV)CCC", "as.factor(IV)DDD"使用
order参数指定所有系数的完整顺序(如果想保留截距项,需要将其包含在内),同时搭配covariate.labels完成重命名:stargazer(model, type = "html", out = "./out/test.html", title = "Title", # 按需求指定所有系数的顺序:先截距,再是你要的四个水平 order = c("(Intercept)", "as.factor(IV)BBB", "as.factor(IV)AAA", "as.factor(IV)DDD", "as.factor(IV)CCC"), # 对应重命名,顺序要和order中的非截距项完全匹配 covariate.labels = c("BBB", "AAA", "DDD", "CCC"))
关键注意事项
- 一定要用
names(coef(model))核对系数名称——哪怕是微小的拼写错误(比如漏空格、因子水平后缀错误)都会导致order参数失效。 - 如果在
order向量中省略截距项,stargazer可能会意外打乱系数顺序,所以如果想让截距项显示在顶部,最好明确将其包含进去。
内容的提问来源于stack exchange,提问作者Ivo

