VitalSigns - 7 months ago 35

R Question

I am new to R and need some help using integration.

I have a function defined as:

`a <- function(t) { exp(-r1*t) }`

I have another function which uses this function and is defined as:

`b <- function(t,x) { a(t-x)* exp(-(1-exp(-r2*x))) }`

where,

`r1`

`r2`

Now, I need to integrate the function

`b(t,x)`

`x`

`0`

`t`

`x <= t`

I am not sure how to proceed with this. I tried the following, but I am not sure how to tell R to integrate over 'x' and not 't'.

`c <- integrate(b, lower=0, upper=10)`

When i run this, I get an error saying:

Error in a(t -x) : argument "t" is missing, with no default

Thanks in advance,

-S

Answer

I am using `r1 = r2 = 1`

as an example.

Since you want a **double integral**:

```
\int_{t=0}^{t=10} \int_{x=0}^{x=t} b(x,t)
```

the most basic approach is to apply `integrate()`

twice.

First, you need to define a **vectorized function** evaluating the inner integral:

```
z <- function(t) sapply(t, function (t_i) integrate(b, lower = 0, upper = t_i, t = t_i)$value)
```

We can check that:

```
z(1:3)
# [1] 0.4225104 0.4440731 0.4150334
```

Now, we apply the outer integral to `z`

:

```
integrate(z, lower = 0, upper = 10)
# 3.795567 with absolute error < 6.2e-06
```

My answer just aims to give you starting point. The linked post: calculating double integrals in R quickly gives you better approach for doing double integral.

Source (Stackoverflow)