How to calculate confidence intervals for a vector? [closed]

放肆的年华 提交于 2019-12-01 14:26:44

问题


I have a vector:

vector <- c(12, 17, 24, 35, 23, 34, 56)

How to calculate confidence intervals (90%, 99%, 95%) for this vector in R?

This is example of result I want: enter image description here


回答1:


Here is a function that will calculate your confidence interval according to the t-distribution:

confidence_interval <- function(vector, interval) {
  # Standard deviation of sample
  vec_sd <- sd(vector)
  # Sample size
  n <- length(vector)
  # Mean of sample
  vec_mean <- mean(vector)
  # Error according to t distribution
  error <- qt((interval + 1)/2, df = n - 1) * vec_sd / sqrt(n)
  # Confidence interval as a vector
  result <- c("lower" = vec_mean - error, "upper" = vec_mean + error)
  return(result)
}

And example usage for your provided vector and intervals:

> vector <- c(12, 17, 24, 35, 23, 34, 56)
> confidence_interval(vector, 0.90)
   lower    upper 
17.97255 39.45602 
> confidence_interval(vector, 0.95)
   lower    upper 
15.18797 42.24060 
> confidence_interval(vector, 0.99)
    lower     upper 
 8.219946 49.208626  

And this is the tutorial from which I developed this method.



来源:https://stackoverflow.com/questions/48612153/how-to-calculate-confidence-intervals-for-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!