在 Execl 或 R 中识别每个样本具有不同数据点数量的异常值

问题描述 投票:0回答:1

我正在尝试识别数据集中的异常点,其中每个样本都有不同数量的数据点。 这意味着矩阵长度因样本而异。 由于我正在处理大数据集,因此手动更改矩阵长度确实非常耗时。 我希望在这里找到该问题的解决方案:) 也欢迎对 R 提出建议!

这是一个示例数据集: enter image description here 我使用的函数: =IF(OR(B2>QUARTILE($B$2:$B$5;3)+1,5*(QUARTILE($B$2:$B$5;3)-QUARTILE($B$2:$ B$5;1));F2

这里有两种方法,用

quantile/IQR
和用统计数据
boxplot
使用。后者最快。

outlier <- function(x, na.rm = FALSE) {
  qq <- quantile(x, c(1/4, 3/4), na.rm = na.rm)
  iqr <- IQR(x, na.rm = na.rm)
  x < qq[1L] - 1.5*iqr | x > qq[2L] + 1.5*iqr
}
outlier_bp <- function(x, na.rm = FALSE) {
  x %in% boxplot.stats(x)$out
}

sapply(iris[1:4], outlier) |> head()
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width
#> [1,]        FALSE       FALSE        FALSE       FALSE
#> [2,]        FALSE       FALSE        FALSE       FALSE
#> [3,]        FALSE       FALSE        FALSE       FALSE
#> [4,]        FALSE       FALSE        FALSE       FALSE
#> [5,]        FALSE       FALSE        FALSE       FALSE
#> [6,]        FALSE       FALSE        FALSE       FALSE
sapply(iris[1:4], outlier_bp) |> head()
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width
#> [1,]        FALSE       FALSE        FALSE       FALSE
#> [2,]        FALSE       FALSE        FALSE       FALSE
#> [3,]        FALSE       FALSE        FALSE       FALSE
#> [4,]        FALSE       FALSE        FALSE       FALSE
#> [5,]        FALSE       FALSE        FALSE       FALSE
#> [6,]        FALSE       FALSE        FALSE       FALSE

library(microbenchmark)

mb <- microbenchmark(
  qnt = sapply(iris[1:4], outlier),
  bxp = sapply(iris[1:4], outlier_bp)
)
print(mb, order = "median")
#> Unit: microseconds
#>  expr   min     lq    mean median     uq    max neval cld
#>   bxp 233.3 321.15 388.300 365.55 454.15  738.9   100   b
#>   qnt 551.2 742.65 875.958 817.95 949.30 3593.9   100  a

创建于 2023-09-25,使用 reprex v2.0.2

r excel matrix outliers
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.