计算R中的人口标准差

时间:2017-06-03 00:24:54

标签: r statistics variance

寻找一种计算R中人口标准差的方法 - 使用大于10个样本。无法在R中提取源C代码以找到计算方法。

# Sample Standard Deviation 
# Note: All the below match with 10 or less samples
n <- 10 # 10 or greater it shifts calculation
set.seed(1)
x <- rnorm(n, 10)

# Sample Standard Deviation
sd(x)
# [1] 0.780586
sqrt(sum((x - mean(x))^2)/(n - 1))
# [1] 0.780586
sqrt(sum(x^2 - 2*mean(x)*x + mean(x)^2)/(n - 1)) # # Would like the Population Standard Deviation equivalent using this.
# [1] 0.780586
sqrt( (n/(n-1)) * ( ( (sum(x^2)/(n)) ) - (sum(x)/n) ^2 ) )
# [1] 0.780586

现在,人口标准偏差需要将sd(x)与100计数匹配。

# Population Standard Deviation 
n <- 100 
set.seed(1)
x <- rnorm(x, 10)

sd(x)
# [1] 0.780586

sqrt(sum((x - mean(x))^2)/(n))
# [1] 0.2341758

sqrt(sum(x^2 - 2*mean(x)*x + mean(x)^2)/(n)) 
# [1] 0.2341758

# Got this to work above using (eventual goal, to fix the below):
# https://en.wikipedia.org/wiki/Algebraic_formula_for_the_variance
sqrt( (n/(n-1)) * ( ( (sum(x^2)/(n)) ) - (sum(x)/n) ^2 ) )  # Would like the Population Standard Deviation equivalent using this.
# [1] 3.064027

4 个答案:

答案 0 :(得分:5)

请检查问题。 rnorm的第一个参数应为n。

人口和样本标准差是:

sqrt((n-1)/n) * sd(x) # pop
## [1] 0.8936971

sd(x) # sample
## [1] 0.8981994

它们也可以这样计算:

library(sqldf)
library(RH2)

sqldf("select stddev_pop(x), stddev_samp(x) from X")
##   STDDEV_POP("x") STDDEV_SAMP("x")
## 1       0.8936971        0.8981994

注意:我们使用了这个测试数据:

set.seed(1)
n <- 100
x <- rnorm(n)
X <- data.frame(x)

答案 1 :(得分:1)

我刚刚花费了相当多的时间来寻找具有针对人口标准偏差的现成功能的包装。这些是结果:

1)radiant.data::sdpop应该是一个很好的功能(请参见documentation

2)multicon::popsd也可以很好地工作,但是请检查documentation来了解第二个参数是什么

3)muStat::stdevunbiased=FALSE不能正常工作。在github页面上,似乎在2012年有人将其设置为sd(x)*(1-1/length(x))而不是sd(x)*sqrt(1-1/length(x)) ...

4)rfml::sd.pop在没有ml.data.frame(MarkLogic Server)的情况下将无法工作

我希望这会有所帮助。

答案 2 :(得分:1)

我认为最简单的方法是从 sd 快速定义它:

sd.p=function(x){sd(x)*sqrt((length(x)-1)/length(x))}

答案 3 :(得分:0)

## Sample Standard Deviation  
n <- 10 # Sample count
set.seed(1)
x <- rnorm(n, 10)

sd(x) # Correct 
# [1] 0.780586
sqrt(sum((x - mean(x))^2)/(n - 1)) # Correct 
# [1] 0.780586
sqrt(sum(x^2 - 2*mean(x)*x + mean(x)^2)/(n - 1)) # Correct 
# [1] 0.780586
sqrt( (n/(n-1)) * ( ( (sum(x^2)/(n)) ) - (sum(x)/n) ^2 ) ) # Correct 
# [1] 0.780586
sqrt((sum(x^2) - (sum(x)^2/n))/(n-1)) # Correct 
# [1] 0.780586
sqrt( (n/(n - 1)) * ( (sum(x^2)/(n))  - (sum(x)/n) ^2 ) ) # Correct 
# [1] 0.780586


## Population Standard Deviation  
n <- 100 # Note: 10 or greater biases var() and sd()
set.seed(1)
x <- rnorm(n, 10)

sd(x) # Incorrect Population Standard Deviation!!
# [1] 0.8981994
sqrt(sum((x - mean(x))^2)/(n)) # Correct
# [1] 0.8936971
sqrt(sum(x^2 - 2*mean(x)*x + mean(x)^2)/(n)) # Correct 
# [1] 0.8936971
sqrt((sum(x^2) - (sum(x)^2/n))/(n)) # Correct
# [1] 0.8936971
sqrt( (n/(n)) * ( (sum(x^2)/(n))  - (sum(x)/n) ^2 ) ) # Correct 
# [1] 0.8936971