Search code examples
rintegral

Calculate definite integral in R bunch of error


I am trying to calculate the following integral, i.e there is an integral inside the integral.

integrate(function(v){
  integrate(function(s){
    pnorm(qnorm(v)-qnorm(s))
  },0,1)$value
},0,1)

Unfortunately I all the time get either:

Error in integrate(function(v) { : 
  evaluation of function gave a result of wrong length

or:

 Error in integrate(function(s) { : maximum number of subdivisions reached 

Solution

  • The error because integrate needs a vectorized function. A workaround is to use Vectorize around the upper function.

    integrate(Vectorize(function(v){
      integrate(function(s){
        pnorm(qnorm(v)-qnorm(s))
      },0,1)$value
    }),0,1)
    
    ## 0.5 with absolute error < 5.6e-15