R中的置信区间(CI)模拟:如何?

时间:2017-08-08 15:21:11

标签: r random statistics sampling confidence-interval

我想知道如何通过R中的模拟检查95%置信区间在15次试验中从二项式测试中获得5次成功 TRUE p = .5 有95%"覆盖率概率"从长远来看?

以下是使用R进行此类测试的95%CI(如果 TRUE p = .5 ,如何显示以下CI在长期内的覆盖率为95%):

as.numeric(binom.test(x = 5, n = 15, p = .5)[[4]])
# > [1] 0.1182411 0.6161963 (in the long-run 95% of the time, ".5" is contained within these
#                            two numbers, how to show this in R?)

1 个答案:

答案 0 :(得分:1)

这样的东西?

fun <- function(n = 15, p = 0.5){
    x <- rbinom(1, size = n, prob = p)
    res <- binom.test(x, n, p)[[4]]
    c(Lower = res[1], Upper = res[2])
}

set.seed(3183)
R <- 10000
sim <- t(replicate(R, fun()))

请注意binom.test调用5次成功,15次试验和p = 0.5时,将始终返回相同的值,因此调用rbinom。成功的数量会有所不同。我们可以计算p介于LowerUpper之间的案例比例。

cov <- mean(sim[,1] <= .5 & .5 <= sim[,2])