向量化R函数中的uniroot()

向量化R函数中的uniroot(),r,function,optimization,linear-algebra,R,Function,Optimization,Linear Algebra,在我下面的函数中,我想知道为什么当我使用一个向量作为参数d时,函数工作得很好,但是当我使用一个向量作为参数t时,函数(从uniroot)抛出错误: f()端点处的值不是相反符号 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

在我下面的函数中,我想知道为什么当我使用一个向量作为参数
d
时,函数工作得很好,但是当我使用一个向量作为参数
t
时,函数(从
uniroot
)抛出错误
f()端点处的值不是相反符号

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`

cii与矢量化无关,但
q
t
的值为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)

我认为他们回答了两个不同的问题。正在查找最大值(确实存在),同时正在查找f=0(不存在)的位置。你的目标是什么?这听起来更像是一个统计/交叉验证问题,而不是一个编程/堆栈溢出问题。我认为算法和函数正在返回正确答案。我想这是找到了ncp的根