首页 > 解决方案 > r 中的绘图错误:“x”和“y”长度不同

问题描述

我想为我的回归绘制残差图。我想像在这里( http://www.r-tutor.com/elementary-statistics/simple-linear-regression/residual-plot)那样绘制它:

model1 <- lm(ROA ~ LN_CO2, data=model1) 
model1.res <- resid(model1)
plot(LN_CO2, model1.res)

但是,我有这个错误:

> plot(LN_CO2, model1.res)
Error in xy.coords(x, y, xlabel, ylabel, log) : 
'x' and 'y' lengths differ

我认为它会发生,因为在计算 'resid()' 缺失值 (NA's) 时,model1.res 和 LN_CO2 的数据量不相等。因此,绘图错误。如果我是对的,我仍然不知道如何使用 na.exclude、na.omit 等。有人可以帮助我吗?

编辑:

我的数据看起来像这样(我有大约 1200 次观察):

残差: -1.345901 -2.124645 -3.614880 -4.703744 7.305482 -4.041825

LN_CO2:( 7.278 7.872 6.902 7.296 8.173 8.335 对不起,如果它不适合复制粘贴,请尽力而为)

标签: rplotna

解决方案


您可以使用您的数据和残差创建一个数据框,只选择完整的案例:

df <- data.frame(LN_CO2, model1.res) df2 <- df[complete.cases(df),]

然后你可以从那里绘制:

plot(df2$LN_CO2, df2$model1.res)


推荐阅读