【问题标题】:How to make `integrate()` to accept a vector in an R function?如何使`integrate()`接受R函数中的向量?
【发布时间】:2017-11-23 09:47:13
【问题描述】:

我想知道如何使我的函数Bpp 接受一个向量作为其第一个参数 t

Bpp = function(t, n1, n2 = NULL){

      N = ifelse(is.null(n2), n1, n1*n2/(n1+n2))
     df = ifelse(is.null(n2), n1 - 1, n1 + n2 - 2)

     H1 = integrate(function(delta)dcauchy(delta, 0, sqrt(2)/2)*dt(t, df, delta*sqrt(N)), -Inf, Inf)[[1]]
     H0 = dt(t, df)
   BF10 = H1/H0
p.value = 2*(1-pt(abs(t), df))

list(BF10 = BF10, p.value = p.value)
}

Bpp(t = -6:6, 20, 20) ## This will give error because `t` is now a vector?

【问题讨论】:

  • Vectorize 在这些情况下通常很有用。虽然重写它以直接接受向量更好。

标签: r function vectorization integral numerical-integration


【解决方案1】:

看起来我可以在不测试的情况下快速给出答案。在您的Bpp 中使用以下内容:

# joint density
joint <- function(delta, t) dcauchy(delta, 0, sqrt(2)/2) * dt(t, df, delta*sqrt(N))
# marginal density of `t`
marginal.t <- function (t) integrate(joint, lower = -Inf, upper = Inf, t = t)[[1]]
H1 <- sapply(t, marginal.t)

那么,这里我们也可以使用Vectorize,那会是什么样子?

使用您原来的Bpp

Bpp <- Vectorize(Bpp, vectorize.args = "t")
Bpp(-6:6, 20, 20)

【讨论】:

    猜你喜欢
    • 2020-08-05
    • 2021-07-10
    • 2018-09-19
    • 2021-04-07
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多