在下面的函数中,我想知道为什么 当我使用 向量d
时,该函数运行良好但是 当我使用 参数t
时,函数( from 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`
答案 0 :(得分:1)
它与向量化无关,但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)