向量化 R 函数中的 uniroot()

uniroot() in vectorized R functions

在下面的函数中,我想知道为什么 当我使用 作为参数 d 的向量时,函数工作正常但是 当我使用 作为参数 t 的向量时,函数( 来自 uniroot ) 抛出错误 : f() values at end points not of opposite sign

cii <- function(d, t = NA, n1, n2 = NA, conf.level = .95){

  ci <- Vectorize(function(d, t, n1, n2, conf.level){

    options(warn = -1)  
    alpha = (1 - conf.level)/2
    N = ifelse(is.na(n2), n1, (n1 * n2)/(n1 + n2))
    df = ifelse(is.na(n2), n1 - 1, (n1 + n2) - 2)
    d.SE = 1/sqrt(N)
    q = ifelse(is.na(t), d/d.SE, t)

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

    CI <- sapply(c(alpha, 1-alpha),
      function(x) uniroot(f, interval = c(0, q+2e2), alpha = x, q = q, df = df)[[1]]*d.SE)
    CI
  })

  d <- if(missing(d)) NA else d

  data.frame(t(ci(d = d, t = t, n1 = n1, n2 = n2, conf.level = conf.level)))
}

# EXAMPLES OF USE:
cii(d = c(2, 3), n1 = 30)  # Works perfectly fine!
cii(t = c(2, 3), n1 = 30)  # Throws error: `f() values at end points not of opposite sign`

与矢量化无关,但是qt的值是2。端点(,0和202)都是负数,所以 uniroot() 假设它不超过零。

> f(ncp=  0, alpha=0.025, q=2, df=29 )
[1] -0.002471819
> f(ncp=202, alpha=0.025, q=2, df=29 )
[1] -0.975

t 为 3 时确实过零。

> f(ncp=  0, alpha=0.025, q=3, df=29 )
[1] 0.0222504
> f(ncp=202, alpha=0.025, q=3, df=29 )
[1] -0.975

此图表明它刚好从零以下开始,并且永远不会接近。

curve(f(ncp=x, alpha=0.025, q=2, df=29 ), 0, 202)