简体   繁体   English

如何计算R中多个标准差的平均值?

[英]How to calculate the average of multiple standard deviations in R?

I am trying to figure out how to calculate the standard deviation of a dataset when I have a couple of standard deviations.当我有几个标准偏差时,我试图弄清楚如何计算数据集的标准偏差。 Let's just look at this MWE:让我们看看这个 MWE:

set.seed(1234)
dummy_data <- data.frame(
  "col_1" = sample(1:7, size = 10, replace = TRUE),
  "col_2" = sample(1:7, size = 10, replace = TRUE),
  "col_3" = sample(1:7, size = 10, replace = TRUE),  
  "col_4" = sample(1:7, size = 10, replace = TRUE)
)

Now since I know all the data points I can calculate the total standard deviation as follows:现在,由于我知道所有数据点,我可以按如下方式计算总标准差:

> sd(as.matrix(dummy_data))
[1] 1.727604

But the real data that I have at hand is the following:但我手头的真实数据如下:

> dplyr::summarise_all(dummy_data, sd)
     col_1    col_2   col_3    col_4
1 1.837873 1.873796 1.37032 1.888562

If I follow the usual method of calculating the average of multiple standard deviations with similar sample sizes, I would apply the following:如果我按照通常的方法计算具有相似样本量的多个标准偏差的平均值,我将应用以下内容:

sds <- dplyr::summarise_all(dummy_data, sd)
vars <- sds^2
mean_sd <- sqrt(sum(vars) / (length(vars) - 1))

> mean_sd
[1] 2.027588

which is not the same!这是不一样的! Now I have tried without the minus one:现在我试过没有减一:

> sqrt(sum(vars) / (length(vars)))
[1] 1.755942

which does not solve the problem.这并不能解决问题。 I have tried defining an own standard deviation function like this:我尝试过定义一个自己的标准偏差函数,如下所示:

own_sd <- function(x) {
  sqrt(sum((x - mean(x))^2) / length(x))
}

to eliminate the x - 1 in the dplyr::summarise_all() step, and then average according to the step above:消除dplyr::summarise_all()步骤中的x - 1 ,然后根据上述步骤进行平均:

> sqrt(sum(dplyr::summarise_all(dummy_data, own_sd)^2) / 3)
[1] 1.923538
> sqrt(sum(dplyr::summarise_all(dummy_data, own_sd)^2) / 4)
[1] 1.665833

But all seem to give a different result than the sd(as.matrix()) method.但似乎都给出了与sd(as.matrix())方法不同的结果。 What is going wrong here?这里出了什么问题?

You can't calculate a global SD from only knowing group SDs.您不能仅通过知道组 SD 来计算全局 SD。 For example:例如:

x1 = 1:5
x2 = 11:15
x3 = 101:105

## all the SDs are equal
(sd1 = sd(x1))
#[1] 1.581139
(sd2 = sd(x2))
#[1] 1.581139
(sd3 = sd(x3))
#[1] 1.581139

## however, combining the groups in pairs give very different results
sd(c(x1, x2))
# [1] 5.477226

sd(c(x1, x3))
# [1] 52.72571

This demonstrates that even if the sample sizes are identical, knowing the standard deviation of two groups does not help you calculate the standard deviation of those groups combined.这表明即使样本量相同,知道两组的标准差也无助于计算这些组的组合标准差。

As per Merijn van Tilborg's comment, if you know the group sizes and the group means, the calculation is possible as shown here .根据 Merijn van Tilborg 的评论,如果您知道组大小和组均值,则可以按此处所示进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM