含交互项多元线性回归中获取变量平均偏效应的高效方法
获取交互项模型中变量的平均偏效应(APE)的高效方法
不用手动计算交互项均值再重新拟合回归,直接用margins包就能一键搞定,这是R里处理边际效应最常用的高效工具。
具体操作步骤:
- 安装并加载
margins包:
install.packages("margins") library(margins)
- 基于你已拟合好的
model,直接计算cathhs的平均偏效应:
# 计算指定变量的平均偏效应 cathhs_ape <- margins(model, variables = "cathhs") # 查看带统计量的结果 summary(cathhs_ape)
也可以一步到位:
summary(margins(model, variables = "cathhs"))
原理说明:
margins包会自动为每个观测计算cathhs的边际效应(也就是回归方程对cathhs求偏导的结果:$\beta_{cathhs} + \beta_{cathhs:lfaminc}*lfaminc + \beta_{cathhs:motheduc}*motheduc + \beta_{cathhs:fatheduc}*fatheduc$),然后对所有观测的边际效应取平均值,得到的就是平均偏效应(APE),全程无需手动处理交互项均值或重构模型。
手动验证(可选):
如果想确认结果准确性,可以手动计算对比:
# 提取回归系数 coefs <- coef(model) # 计算每个观测的边际效应 marg_eff <- coefs["cathhs"] + coefs["cathhs:lfaminc"]*catholic$lfaminc + coefs["cathhs:motheduc"]*catholic$motheduc + coefs["cathhs:fatheduc"]*catholic$fatheduc # 取平均得到手动计算的APE manual_ape <- mean(marg_eff) # 与margins结果对比 manual_ape
这个手动计算结果会和margins输出的AME(平均边际效应,与APE概念一致)完全吻合。
内容的提问来源于stack exchange,提问作者AKJ
相关产品推荐
相关产品推荐

