R中混合回归与固定效应组内估计量x/y长度不一致问题求解
面板模型绘图报错:x与y长度不匹配问题排查
问题描述
我正在R中开展面板数据分析,使用plm包拟合混合回归(pooled regression)与固定效应组内估计量(fixed effects within estimator)模型,代码如下:
m_pooled = plm(homiciderate ~ humanrightsviol + freedom + lngdp + econgrowth + popdensity + male1564, data = df_hom, index = c("country","year"), model="pooling") m_fixedeffects <- plm(homiciderate ~ humanrightsviol + freedom + lngdp + econgrowth + popdensity + male1564, data = df_hom, index = c("country","year"), model="within")
尝试合并两个模型的结果绘图时,使用以下代码:
plot_fixedeffects <- plot(m_fixedeffects, type = "effects", index = 2, col = "red") plot_pooled <- plot(m_pooled, type = "effects", index = 2, col = "blue") combined_plot <- plot_fixedeffects + plot_pooled combined_plot <- combined_plot + labs(title = "Fixed Effects Within Estimator vs Pooled Regression", x = "Time", y = "Effect Estimate") + scale_color_manual(values = c("red", "blue"), labels = c("Fixed Effects Within Estimator", "Pooled Regression"), name = "Estimation Method") print(combined_plot)
出现错误信息:
Error in xy.coords(x, y) : 'x' and 'y' lengths differ In addition: Warning message: In meanx * beta : longer object length is not a multiple of shorter object length
期望得到类似示例图的结果,但无法实现,请问该问题的原因是什么?
问题原因分析
plm基础绘图不支持ggplot拼接语法plm包自带的plot()函数生成的是基础R绘图(base plot),并非ggplot2的图层对象,不能用+运算符直接合并。强行用ggplot的方式拼接两个基础绘图,会导致R无法识别对象结构,触发x/y维度不匹配的错误。混合回归与固定效应的"effects"输出逻辑不一致
当指定type="effects"时:- 固定效应模型(
model="within")输出的是组内个体/时间效应值,对应每个面板单元的效应估计; - 混合回归(
model="pooling")本质是普通OLS,没有组内效应的概念,它的"effects"输出是基于系数的拟合值或线性组合,两者的输出长度、维度完全不匹配,这是报错的直接触发点。
- 固定效应模型(
绘图逻辑与目标图不符
你参考的示例图应该是展示模型系数估计对比或时间/个体效应的趋势对比,但当前代码直接调用plot(plm_object, type="effects")的逻辑错误:混合回归没有组内效应,无法和固定效应的效应值进行对齐绘图。
内容的提问来源于stack exchange,提问作者CharlieMac30
相关产品推荐
相关产品推荐

