2017-06-20 102 views
1

我在想如何讓我的功能Bpp接受一個向量作爲它的第一個參數t如何讓`integration()`在R函數中接受一個向量?

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? 
+0

'Vectorize'在這些情況下,通常是有用的。雖然重寫它直接接受矢量更好。 – Dason

回答

2

看起來像我可以給一個快速的答案沒有測試。使用以下在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) 
相關問題