数据帧错误* tmp *替换为x数据为y [英] Error in dataframe *tmp* replacement has x data has y

查看:240
本文介绍了数据帧错误* tmp *替换为x数据为y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R语言的初学者.这是一个非常简单的代码,我试图保存剩余项:

I'm a beginner in R. Here is a very simple code where I'm trying to save the residual term:

# 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创建了完全相同的代码,它可以很好地保存剩余部分,没有任何错误.如果有人可以帮助我解决此问题,我将不胜感激.

I searched for this error but couldn't find anything that could resolve this. Additionally, I've created the exact same code for mom's EA, and it saved the residual just fine, with no errors. I'd be grateful if someone could help me resolve this.

推荐答案

我觉得您的数据中有NA个.看这个例子:

I have a feeling you have NAs in your data. Look at this example:

#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

如您所见,这将导致与您类似的错误.

As you can see this results in a similar error to yours.

作为验证:

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

之所以会发生这种情况,是因为lm将在运行回归之前在数据集上运行na.omit,因此,如果您有任何包含NA的行,这些行将被消除,从而导致结果更少.

This happens because lm will run na.omit on the data set prior to running the regression, so if you have any rows with NA these will get eliminated resulting in fewer results.

如果您在dat数据集(即dat <- na.omit(dat)在代码的开始处)上运行na.omit,则您的代码应该可以工作.

If you run na.omit on your dat data set (i.e. dat <- na.omit(dat) at the very beginning of your code then your code should work.

这篇关于数据帧错误* tmp *替换为x数据为y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆