# [R] two dimensional integration

Berend Hasselman bhh at xs4all.nl
Sun Feb 17 09:41:54 CET 2013

```On 16-02-2013, at 18:01, julia cafnik <julia.cafnik at gmail.com> wrote:

> Dear R-users,
>
> I'm wondering how to calculate this double integral in R:
>
> int_a^b  int_c^y g(x, y) dx dy
>
> where g(x,y) = exp(- alpha (y - x)) * b
>

In your case define function g (leave out the multiply by b since you can always do that outside the integral).

g <- function(x,y,alpha=1) exp(-alpha*(y-x))

Assume a=0, b=1 and c=0.

Then following the final message in the thread mentioned above there are two ways of getting an answer:

if function g is fully vectorized:

integrate( function(y) {
sapply(y, function(y) {
integrate(function(x) g(x,y),0,y)\$value
})
},0,1)

and if g is not vectorized and only takes scalars as input

integrate(function(y) {
sapply(y, function(y) {
integrate(function(x) {
sapply(x, function(x) g(x,y)) },0,y)\$value
})
},0,1)

Both of the approaches result in

0.3678794 with absolute error < 4.1e-15

which corresponds to the exact analytical answer 1/exp(1) (if I didn't make a mistake)

You can also do this with package cubature with Gabor's approach (from the mentioned thread) like this

library(cubature)
h <- function(z) g(z,z)*(z<z)

but it's also very slow with higher tolerances.

\$integral
 0.3678723
\$error
 3.677682e-05
\$functionEvaluations
 268413
\$returnCode
 0

Berend

```