Search code examples
rbayesianintegral

Coding a multiple integral function in R


With the goal of turning the following into a function, I was wondering how I can write the following double integral in terms of R codes?: ($\bar{x} = \mu$):

enter image description here


Solution

  • Assuming pi0 and pi1 implement your functions $\pi_0$ and $\pi_1$ in a vectorized way, a possible solution is:

    integral <- function(n, mu, s, pi0, pi1) {
    
      C <- (2 * pi)^(-n/2) 
      C * integrate(f = function(sigmavec) sapply(sigmavec, function(sigma) {
        integrate(f = function(delta) {
    
          exp(-n/2 * ((mu / sigma - delta)^2 + (s / sigma)^2)) * pi1(delta)
    
        }, lower = -Inf, upper = Inf)$value
    
      }) * pi0(sigmavec) / (sigmavec^n), lower = 0, upper = Inf)$value
    
    }
    
    # Tests
    integral(n = 1, mu = 0, s = 1, pi0 = dnorm, pi1 = dnorm)
    # [1] 0.0473819
    integral(n = 1, mu = 0, s = 1, pi0 = function(sigma) 1/sigma, pi1 = dcauchy)
    # [1] 0.2615783