【问题标题】:Compute standard deviation with a manually set mean in R在 R 中使用手动设置的平均值计算标准偏差
【发布时间】:2021-12-04 12:45:34
【问题描述】:

我知道如何使用汇总计算 sd:

ans <- temp%>% group_by(permno)%>%  summarise(std = sd(ret)))

但是,如果我知道平均值 = 0,我该如何计算标准差?

换句话说,我知道真正的均值,并希望在计算 sd 时使用它而不是使用样本均值。

一种方法是手动编码 sd 函数,但我需要它为每个组工作,所以我被卡住了。

【问题讨论】:

  • 可能是mad() 函数,带有“center=0”?

标签: r standard-deviation


【解决方案1】:

最好提供可重现的数据。以下是 iris 数据集的示例:

data(iris)
GM <- mean(iris$Sepal.Length)  # "Population mean"
ans <- iris %>% group_by(Species) %>% summarise(std=sum((Sepal.Length - GM)^2)/length(Sepal.Length))
ans
# A tibble: 3 × 2
#   Species      std
#   <fct>      <dbl>
# 1 setosa     0.823
# 2 versicolor 0.270
# 3 virginica  0.951

与用每组均值计算 sd 相比:

ans <- iris %>% group_by(Species) %>% summarise(std=sd((Sepal.Length)))
ans
# A tibble: 3 × 2
#   Species      std
#   <fct>      <dbl>
# 1 setosa     0.352
# 2 versicolor 0.516
# 3 virginica  0.636

请注意,sd 在分母中使用“n - 1”,但由于您指出您的均值是总体均值,因此我们使用 n

【讨论】:

    【解决方案2】:

    我想出了这个解决方案:

    sd_fn <- function(x, mean_pop) {
      sd_f <- sqrt((sum((x-mean_pop)^2))/(length(x)))
      sd_f
    }
    
    x <- c(1,2,3,-1,-1.5,-2.8)
    mean_pop <- 0
    
    sd_fn(x, mean_pop)
    
    

    我只是创建了一个函数,其中参数是数字向量,总体意味着您已经知道...只需输入带有数据和平均总体的向量,该函数将为您提供所需的标准偏差。

    【讨论】:

      【解决方案3】:

      您好,如果想从真实均值计算 sd,我认为您可以通过对样本向量的平方差使用均值函数和真实均值来计算方差,然后使用 sqrt 来计算标准偏差。请记住,base R 的 var 和 sd 函数具有自动贝塞尔校正,您可以阅读https://www.r-bloggers.com/2018/11/how-to-de-bias-standard-deviation-estimates/

      #Sample Size
      n=1000
      #sample Random Vec
      universe = rnorm(n,0,3)
      
      # sample mean 
      p = mean(universe)
      p
      # true mean
      p0 = 0
      
      # calculate "manually" using sample mean
      variance <- mean((universe - p)^2)
      variance
      
      standard_deviation <- sqrt(variance)
      standard_deviation
      
      # calculate "manually" usingtrue mean
      
      variance_true <- mean((universe - p0)^2)
      variance_true
      
      standard_deviation_true <- sqrt(variance_true)
      standard_deviation_true
      # calculate using built in R functions 
      var_r<-var(universe)
      var_r
      r_sd<-sd(universe)
      r_sd
      
      # They have automatic Bessels correction :
      variance * n/(n-1) == var_r # Bessels correction using  * n/(n-1) 
      
      r_sd == sqrt(variance * n/(n-1) )
      
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        • 2018-02-01
        • 2014-03-21
        • 2021-05-22
        相关资源
        最近更新 更多