【发布时间】:2012-10-11 20:38:34
【问题描述】:
我正在尝试遍历向量以使用 IQR 来计算范围来查找异常值。当我运行此脚本以查找 IQR 右侧的值时,我得到结果,当我向左运行时,我得到错误:缺少 TRUE/FALSE 需要的值。如何清除数据集中的真假? 这是我的脚本:
data = c(100, 120, 121, 123, 125, 124, 123, 123, 123, 124, 125, 167, 180, 123, 156)
Q3 <- quantile(data, 0.75) ##gets the third quantile from the list of vectors
Q1 <- quantile(data, 0.25) ## gets the first quantile from the list of vectors
outliers_left <-(Q1-1.5*IQR(data))
outliers_right <-(Q3+1.5*IQR(data))
IQR <- IQR(data)
paste("the innner quantile range is", IQR)
Q1 # quantil at 0.25
Q3 # quantile at 0.75
# show the range of numbers we have
paste("your range is", outliers_left, "through", outliers_right, "to determine outliers")
# count ho many vectors there are and then we will pass this value into a loop to look for
# anything above and below the Q1-Q3 values
vectorCount <- sum(!is.na(data))
i <- 1
while( i < vectorCount ){
i <- i + 1
x <- data[i]
# if(x < outliers_left) {print(x)} # uncomment this to run and test for the left
if(x > outliers_right) {print(x)}
}
我得到的错误是
[1] 167
[1] 180
[1] 156
Error in if (x > outliers_right) { :
missing value where TRUE/FALSE needed
如您所见,如果您运行此脚本,它会在右侧找到我的 3 个异常值并引发错误,但是当我在 IQR 左侧再次运行此脚本时,我确实有 100 个异常值向量,我只是得到错误而没有显示其他结果。 如何修复此脚本?非常感谢任何帮助。几天来,我一直在网上和我的书上搜索如何解决这个问题。
【问题讨论】:
-
i=16会出错。比较后切换i<-i+1。 -
您正在切换该语句的位置,以便在比较之后发生。
-
你让
i等于向量数据的长度,然后加1然后索引,因此它返回NA和if语句逻辑语句失败