有很多种方法可以做到这一点。一个简单的策略是首先将您的残差保存为data.frame
作为新列。然后,您可以添加第二个新列来标记残差是否异常。然后,您可以使用该栏来创建一个新的data.frame
,而无需异常值或子集当前data.frame
或您需要的任何其他值。这里有一个例子:
set.seed(20) #sets the random number seed.
# Test data and test linear model
DF<-data.frame(X=rnorm(200), Y=rnorm(200), Z=rnorm(200))
LM<-lm(X~Y+Z, data=DF)
# Store the residuals as a new column in DF
DF$Resid<-resid(LM)
# Find out what 2 standard deviations is and save it to SD2
SD2<-2*sd(resid(LM))
SD2
#[1] 1.934118
# Make DF$Outs 1 if a residual is 2 st. deviations from the mean, 0 otherwise
DF$Outs<-ifelse(abs(DF$Resid)>SD2, 1, 0)
# Plot this, note that DF$Outs is used to set the color of the points.
plot(DF$Resid, col=DF$Outs+1, pch=16,ylim=c(-3,3))
#Make a new data.frame with no outliers
DF2<-DF[!DF$Outs,]
nrow(DF2)
#[1] 189 Was 200 before, 11 outliers removed
# Plot new data
plot(DF2$Resid, col=DF2$Outs+1,pch=16, ylim=c(-3,3))
这是基本的想法。您可以结合其中一些命令 - 例如,您可以创建异常值列而不保存SD2
,而且您并不需要两个data.frames
- 只需在需要时排除异常值行即可。
请用一些示例数据编辑您的文章。有关在R中创建可重复示例的提示,请参阅[此问题](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – voidHead 2014-10-08 00:12:17
如果你有超过200分的排位赛资格,你会如何决定排除哪些排位? – 2014-10-08 00:22:06
我不知道!你有什么建议吗?我甚至不知道我的数据框有多少离群值! – 2014-10-08 00:39:51