如何计算R中的二项式置信区间?
在本文中,我们将讨论如何在 R 编程语言中计算二项式置信区间。我们可以使用以下公式计算二项式置信区间:
p +/- z*(√p(1-p) / n)
where,
- p is for the proportion of successes
- z is the chosen value
- n is the sample size
我们可以使用以下方法计算
方法一:使用 prop.test()函数
此函数用于计算 95% 二项式置信区间。
Syntax: prop.test(x, n, conf.level=.95, correct=FALSE)
where,
- x is the input variable
- n is the sample size
- conf.level is the confidence level which is used to calculate the 95% binomial confidence interval.
R
# calculate for 34
print(prop.test(x = 34, n = 100,
conf.level = .95,
correct = FALSE))
R
# load the library
library(Hmisc)
# calculate for 34 with 95%confidence level
print(binconf(x=34, n=100,
alpha=.05))
R
# p value
p = 52/56
# alpha value
a = 0.05
# calculate binomial interval
print(p + c(-qnorm(1-a/2),
qnorm(1-a/2))*sqrt((1/100)*p*(1-p)))
输出:
1-sample proportions test without continuity correction
data: 34 out of 100, null probability 0.5
X-squared = 10.24, df = 1, p-value = 0.001374
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.2546152 0.4372227
sample estimates:
p
0.34
方法二:使用 binconf()函数
binconf()函数在 Hmisc 包中可用。要安装此软件包,请运行以下命令:
install.packages("Hmisc")
binconf() 的语法:
Syntax: binconf(x, n, alpha)
where
- x is the input variable
- n is the sample size
- alpha is the binomial confidence level
R
# load the library
library(Hmisc)
# calculate for 34 with 95%confidence level
print(binconf(x=34, n=100,
alpha=.05))
输出:
PointEst Lower Upper
0.34 0.2546152 0.4372227
方法三:用公式计算置信区间
在此方法中,我们将使用以下公式在 R 中使用二项式置信区间:
Syntax: p + c(-qnorm(1-a/2), qnorm(1-a/2))*sqrt((1/100)*p*(1-p))
where,
- p is the proportional value
- a is the significance level
R
# p value
p = 52/56
# alpha value
a = 0.05
# calculate binomial interval
print(p + c(-qnorm(1-a/2),
qnorm(1-a/2))*sqrt((1/100)*p*(1-p)))
输出:
[1] 0.8780946 0.9790482