- > # the likelihood for parameter sigma and rho
- > bvn_likelihood = function(x,sigma,rho){
- + n = length(x)/2; a = x[,1]; b = x[,2]
- + p = matrix(0,1,n)
- + for (i in 1:n){
- + ab =(a^2 - 2*rho * a * b + b^2)/(2 * (1 - rho^2)*sigma^2)
- + p = exp(-ab)/(2*pi*sigma^2*sqrt(1-sigma^2))
- + }
- + prod(p)
- + }
- >
- >
- > #the prior density for sigma and rho
- > bvn_prior = function(sigma, rho) exp(-sigma)/(4*sqrt(abs(rho)))
- >
- >
- > #the normalizing constant for the posterior distribution
- > bvn_normalize = function(x){
- + integrate2 = function(f, sigma.lower, sigma.upper, rho.lower, rho.upper) {
- + f2 = function(rho) integrate(f, lower = sigma.lower, upper = sigma.upper, rho = rho)$value
- + f3 = function(rho) sapply(rho, f2)
- + integrate(f3, rho.lower, rho.upper)
- + }
- + f = function(sigma, rho) bvn_likelihood(x=x,sigma, rho)*bvn_prior(sigma, rho)
- + integrate2(f, 0, Inf, 0, 1)$value +integrate2(f, 0, Inf, -1, 0)$value
- + a = integrate2(f, 0, Inf, 0, 1)$value; b = integrate2(f, 0, Inf, -1, 0)$value
- + a+b
- + }
- >
- > #the marginal posterior density of rho
- > bvn_posterior_rho = function(x, rho){
- + integrate (function(sigma) {
- + bvn_normalize(x)*bvn_likelihood(x, sigma, rho)*bvn_prior(sigma, rho)}, 0, Inf) $value
- + }
- >
- > # the maginal prior density for rho
- > bvn_prior_rho = function(rho) integrate(function(sigma) bvn_prior(sigma, rho), 0, Inf)
- >
- > set.seed(1)
- > n <- 40
- > x1 <- rnorm(n); x2 <- rnorm(n); z <- rnorm(n)
- > Xa <- cbind (x1, x2); Xb <- cbind (x1+0.5*z, x2+0.5*z)
- > sigma_a = sd(Xa); sigma_b = sd(Xb)
- >
- > bvn_normalize(Xa)
Error in integrate(f, lower = sigma.lower, upper = sigma.upper, rho = rho) :
non-finite function value
In addition: There were 50 or more warnings (use warnings() to see the first 50)
請問 有哪位大神會啊~~知道哪里錯了 能幫忙改一下 問了好多人了 都不會。。!