Is there an R function that handles double integrals where the region of the inner integration is a function of the outer variable? That is to say, while f(x) is integrated from -5 to 5, g(y) is integrated over 0 to h(x).
Thanks, JD
See the function integral2
in the pracma package which does exactly what you are asking for. Here is one of the examples from the help page:
## Compute the volume of a sphere
f <- function(x, y) sqrt(1 -x^2 - y^2)
xmin <- 0; xmax <- 1
ymin <- 0; ymax <- function(x) sqrt(1 - x^2)
I <- integral2(f, xmin, xmax, ymin, ymax)
I$Q # 0.5236076 - pi/6 => 8.800354e-06
where one of the limits, ymax
, is a function while the other limits are constants, but could also be functions.
You can use the adaptIntegrate
function from the cubature
library. I will assume for the sake of an example that your function is f(x, y) = x + y
:
library(cubature)
fun <- function(x) x[1] + x[2]
adaptIntegrate(fun, c(0, 10), c(-5, 5), tol=1e-8)
This integrates over y
from 0 to 10, then over x
from -5 to 5.
Note that adaptIntegrate
does not appear to accept a function as integral bounds. So if you want to the outer integral to go from 0 to h(x)
you will probably have to write your own quadrature (not a hard thing to do).