R:标记异常值的错误(R 如何识别无限小数的长度)

R: bugs in flagging outliers (how R recognizes the length of a infinite decimal)

我遇到了问题运行 流畅的代码:

library("outliers")

#flags the outliers
grubbs.flag <- function(x) {
  outliers <- NULL
  test <- x
  grubbs.result <- grubbs.test(test)
  pv <- grubbs.result$p.value
  while(pv < 0.05) {
    outliers <- c(outliers,as.numeric(strsplit(grubbs.result$alternative," ")[[1]][3]))
    test <- x[!x %in% outliers]
    grubbs.result <- grubbs.test(test)
    pv <- grubbs.result$p.value
  }
  return(data.frame(X=x,Outlier=(x %in% outliers)))
}

# make a vector consists of infinite decimals as an example
a=c(1,5,7,9,110)
b=c(3,3,3,3,3)
x=a/b
grubbs.flag(x)

代码原文来自 How to repeat the Grubbs test and flag the outliers

如果向量 x 由无限小数组成,当存在异常值时,test <- x[!x %in% outliers] 可能会出错。

test <- x[!x %in% outliers] 中,无限小数outliers 不被识别为x 的元素,并陷入无限循环。原因可能是 x 中异常值的长度与 outliers

中的异常值长度不同

所以我很好奇R是如何识别无限小数向量的长度的,以及如何处理这个问题

有几种方法可以解决这个问题。您可以使用 all.equal 或只是测试以查看数字是否几乎相同。

grubbs.flag <- function(x, tol=1e-9) {
    check <- function(a, b) any(abs(a - b) < tol)                    # check for nearly equal
    outliers <- NULL
    test <- x
    grubbs.result <- grubbs.test(test)
    pv <- grubbs.result$p.value
    while(pv < 0.05) {
        outliers <- c(outliers,as.numeric(strsplit(grubbs.result$alternative," ")[[1]][3]))
        inds <- sapply(test, check, outliers)                        # replace the %in% test
        test <- test[!inds]
        grubbs.result <- grubbs.test(test)
        pv <- grubbs.result$p.value
    }
    return(data.frame(X=x,Outlier=sapply(x, check, outliers)))       # replace %in% test
}

a=c(-1e6, 1,5,7,9,110, 1000)
b=3
c=a/b
grubbs.flag(c)

#              X Outlier
# 1 -3.333333e+05  TRUE
# 2 3.333333e-01   FALSE
# 3 1.666667e+00   FALSE
# 4 2.333333e+00   FALSE
# 5 3.000000e+00   FALSE
# 6 3.666667e+01    TRUE
# 7 3.333333e+02    TRUE

最后我用了所有的all.equal函数来解决这个问题,对我来说效果很好。只是使用愚蠢的循环! ╮(╯◇╰)╭

library(outliers)

# comparing the value of vectors element-wise
match_allequal=function(x,y){
  Logical_i=FALSE
  for(i in 1:length(y)){
    Logical_j=NULL
    for( j in 1:length(x)){
      Logical_j=c(Logical_j,isTRUE(all.equal(x[j],y[i])))
    }
    Logical_i=Logical_j|Logical_i
  }
  return (Logical_i)
}

#flags the outliers
grubbs.flag <- function(x) {
  outliers <- NULL
  test <- x
  grubbs.result <- grubbs.test(test)
  pv <- grubbs.result$p.value
  while(pv < 0.05) {
    outliers <- c(outliers,as.numeric(strsplit(grubbs.result$alternative," ")[[1]][3]))
    test <- x[!match_allequal(x,outliers)]
    grubbs.result <- grubbs.test(test)
    pv <- grubbs.result$p.value
  }
  return(data.frame(X=x,Outlier=match_allequal(x,outliers)))
}