R建立残差线性模型时的可变长度差异 [英] R Variable Length Differ when build linear model for residuals
问题描述
我正在研究一个我想使用其他两个线性模型的残差来构建线性模型的问题.我使用UN3数据集来展示我的问题,因为它比使用我的实际数据集更容易将问题放在这里.
I am working on a problem where I want to build a linear model using residuals of two other linear models. I have used UN3 data set to show my problem since its easy put the problem here than using my actual data set.
这是我的R代码:
head(UN3)
m1.lgFert.purban <- lm(log(Fertility) ~ Purban, data=UN3)
m2.lgPPgdp.purban <- lm(log(PPgdp) ~ Purban, data=UN3)
m3 <- lm(residuals(m1.lgFert.purban) ~ residuals(m2.lgPPgdp.purban))
这是我遇到的错误:
> m3 <- lm(residuals(m1.lgFert.purban) ~ residuals(m2.lgPPgdp.purban))
Error in model.frame.default(formula = residuals(m1.lgFert.purban) ~ residuals(m2.lgPPgdp.purban), :
variable lengths differ (found for 'residuals(m2.lgPPgdp.purban)')
我并不太真正理解为什么会发生此错误.如果是与日志相关的问题,那么在构建前两个模型时应该会出现错误.
I am not really understanding the why this error actually take place. If it was log related issue then I should have gotten the error when I am building first two models.
推荐答案
您的默认na.action
最有可能是na.omit
(请检查options("na.action")
).这意味着NA
值会被静默删除,从而导致残差矢量的长度不同.您可能要使用na.action="na.exclude"
,用NA
s填充残差.
Your default na.action
is most likely na.omit
(check with options("na.action")
). This means that NA
values get removed silently, resulting in different lengths of the residuals vectors. You probably want to use na.action="na.exclude"
, which pads the residuals with NA
s.
library(alr3)
options("na.action")
#$na.action
#[1] "na.omit"
m1.lgFert.purban <- lm(log(Fertility) ~ Purban, data=UN3,na.action="na.exclude")
m2.lgPPgdp.purban <- lm(log(PPgdp) ~ Purban, data=UN3,na.action="na.exclude")
m3 <- lm(residuals(m1.lgFert.purban) ~ residuals(m2.lgPPgdp.purban))
#Coefficients:
# (Intercept) residuals(m2.lgPPgdp.purban)
# -0.01245 -0.18127
这篇关于R建立残差线性模型时的可变长度差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!