2017-11-10 192 views
1

我在R.初学者这是一个非常简单的代码,我正在努力挽救残差项:错误在数据帧* TMP *替换为X的数据都有Ÿ

# Create variables for child's EA: 

dat$cldeacdi <- rowMeans(dat[,c('cdcresp', 'cdcinv')],na.rm=T) 
dat$cldeacu <- rowMeans(dat[,c('cucresp', 'cucinv')],na.rm=T) 

# Create a residual score for child EA: 

dat$cldearesid <- resid(lm(cldeacu ~ cldeacdi, data = dat)) 

我得到以下消息:

Error in `$<-.data.frame`(`*tmp*`, cldearesid, value = c(-0.18608488908881, : 
    replacement has 366 rows, data has 367 

我搜索了此错误,但找不到任何可以解决此问题的内容。另外,我为妈妈的EA创建了完全相同的代码,并且保存了残差,没有错误。如果有人能帮我解决这个问题,我将不胜感激。

回答

1

我有一种感觉,你在你的数据中有NA s。看看这个例子:

#mtcars data set 
test <- mtcars 
#adding just one NA in the cyl column 
test[2, 2] <- NA 

#running linear model and adding the residuals to the data.frame 
test$residuals <- resid(lm(mpg ~ cyl, test)) 
Error in `$<-.data.frame`(`*tmp*`, "residuals", value = c(0.382245430809409, : 
    replacement has 31 rows, data has 32 

正如你可以看到这会导致与你类似的错误。

作为一个验证:

length(resid(lm(mpg ~ cyl, test))) 
#31 
nrow(test) 
#32 

这是因为lm将运行在数据之前运行的回归设定na.omit,因此,如果您有任何NA行这些都将被淘汰,导致较少的结果。

如果您在dat数据集运行na.omit(即dat <- na.omit(dat)在你的代码的最开始那么你的代码应该工作。

+0

谢谢你这么多!你上点是对的! –

+0

很高兴能帮助你。 – LyzandeR

+0

其实,我刚刚注意到,当我运行na.omit时,它会清除我的数据集,就像在-0变量中观察我的变量...为什么会这样? –