如何计算一个数值矢量中的异常值的数量

发布于 2025-02-03 19:15:04 字数 59 浏览 1 评论 0原文

我将如何计算数值向量中的离群值的数量,在该数值向量中,将异常值定义为远离平均值超过3个标准偏差的数据点?

How would I count the number of outliers in a numerical vector where an outlier is defined as any datapoint that is more than 3 standard deviations away from the mean?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娜些时光,永不杰束 2025-02-10 19:15:05

如果您的向量被称为x,则可以

sum(abs(x - mean(x)) > (3 * sd(x)))

通过在x中的每个值和整个向量的平均值(abs(x--)中找到每个值之间的绝对距离(x-),可以做到这一点。平均(x))),然后测试以下哪个值大于3 * SD(x)。结果是truefalse的逻辑向量,如果我们sum IT,我们获得了true的总数代码>向量中的值。

例如:

set.seed(1) # For reproducibility

x <- rnorm(10000) # Draw 10,000 elements from N(0, 1)

mean(x)
#> [1] -0.006537039

sd(x)
#> [1] 1.012356

# Find whether each element in x is an outlier or not
outliers <- abs(x - mean(x)) > (3 * sd(x))

# Show the outliers
x[outliers]
#>  [1]  3.810277  3.055742 -3.213189  3.639574 -3.253220  3.153971 -3.539586
#>  [8]  3.064524 -3.208057 -3.202110 -3.071243 -3.671300 -3.119118 -3.232610
#> [15]  3.624361 -3.060042 -3.147046  3.376912 -3.450502 -3.227233  3.093395
#> [22]  3.111203 -3.187454

# Count the outliers
sum(abs(x - mean(x)) > (3 * sd(x)))
#> [1] 23

在2022-06-01创建的 reprex package (v2.0.1)

If your vector is called x you can do

sum(abs(x - mean(x)) > (3 * sd(x)))

This works by finding the absolute distance between each value in x and the mean of the whole vector ( abs(x - mean(x)) ), then testing which of these values is greater than 3 * sd(x). The result is a logical vector of TRUE and FALSE, and if we sum it, we get the total number of TRUE values in the vector.

For example:

set.seed(1) # For reproducibility

x <- rnorm(10000) # Draw 10,000 elements from N(0, 1)

mean(x)
#> [1] -0.006537039

sd(x)
#> [1] 1.012356

# Find whether each element in x is an outlier or not
outliers <- abs(x - mean(x)) > (3 * sd(x))

# Show the outliers
x[outliers]
#>  [1]  3.810277  3.055742 -3.213189  3.639574 -3.253220  3.153971 -3.539586
#>  [8]  3.064524 -3.208057 -3.202110 -3.071243 -3.671300 -3.119118 -3.232610
#> [15]  3.624361 -3.060042 -3.147046  3.376912 -3.450502 -3.227233  3.093395
#> [22]  3.111203 -3.187454

# Count the outliers
sum(abs(x - mean(x)) > (3 * sd(x)))
#> [1] 23

Created on 2022-06-01 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文