简体   繁体   English

向量化R函数中的uniroot()

[英]uniroot() in vectorized R functions

In my function below, I'm wondering why when I use a vector for argument d , the function works fine BUT when I use a vector for argument t , the function ( from uniroot ) throws the error : f() values at end points not of opposite sign 在下面的函数中,我想知道为什么当我将向量用作参数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`

It's not related to vectorization, but the value of q with t is 2. The endpoints ( ie , 0 and 202) are both negative, so uniroot() assumes it doesn't cross zero. 它与向量化无关,但是带有tq的值为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

It does cross zero when t is 3. 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

This graph suggests it starts just below zero, and never gets close. 该图表明它刚好在零以下,并且永远不会接近。

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

从来没有交叉盘零

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM