R

时间:2017-08-08 23:39:34

标签: r random statistics sampling confidence-interval

我有一个R函数,它为t分布的 ncp (非中心性参数)提供95%置信区间。

通过R中的模拟,可以证明从长期来看,来自此R函数的CI捕获给定的 TRUE ncp (此处“2”与输入 t <相同/ em>)95%的时间?

(我很欣赏有关如何做到这一点的任何想法)

CI.ncp <- function(t, N){

  f <- function (ncp, alpha, q, df) {  
abs(suppressWarnings(pt(q = t, df = N - 1, ncp, lower.tail = FALSE)) - alpha) }

sapply(c(0.025, 0.975),
function(x) optim(1, f, alpha = x, q = t, df = N - 1, control = list(reltol = (.Machine$double.eps)))[[1]]) }

#Example of Use:
CI.ncp(t = 2, N = 20) # gives: -0.08293755  4.03548862 

#(in the long-run 95% of the time, "2" is contained within these
# two numbers, how to show this in R?)

以下是我尝试过但没有成功的事情:

fun <- function(t = 2, N = 20){

  ncp = rt(1, N - 1, t)
  CI.ncp(t = 2, N = 20)
  mean(ncp <= 2 & 2 <= ncp )
   }

 R <- 1000
 sim <- t(replicate(R, fun()))
 coverage <- mean(sim[,1] <= 2 & 2 <= sim[,2])

2 个答案:

答案 0 :(得分:0)

问题在于我们需要提供TTimeZone.Localncp获得的随机fun

CI.ncp

答案 1 :(得分:0)

我会使用包MBESS

#install.packages("MBESS")
library(MBESS)

fun <- function(t = 2, N = 20, alpha = 0.95){
   x = rt(1, N - 1, t)
   conf.limits.nct(x, df = N, conf.level = alpha)[c(1, 3)]
}

set.seed(5221)
R <- 1000
sim <- t(replicate(R, fun()))
head(sim)
coverage <- mean(sim[,1] <= 2 & 2 <= sim[,2])
coverage
[1] 0.941