1

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 and r2 are constants.

Now, I need to integrate the function b(t,x) for values of x that range from 0 to t; given that 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

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
VitalSigns
  • 83
  • 2
  • 10

2 Answers2

3

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.

Community
  • 1
  • 1
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
0

First thing, I allways wouldn't use parameters in a function that aren't parsed to it if not really necessary. So I would write a <- function(t, r1) { exp(-r1*t) } and b <- function(t, x, r2) { a(t-x)* exp(-(1-exp(-r2*x))) } (there was also a closing bracket missing). Second Thing, I wouldn't name results (and other objects) c as this is already a function name in R. Third thing, your question didn't say what Nd_theta is, so I assume it is b. Forth thing, you parse the function Nd_theta to integrate and not ist result Nd_theta(...). Related next thing: the error message doesn't occur because of integrate, but because Nd_theta needs two arguments (presumably x and t) to work and you don't specify them when just coding Nd_theta(). You can check this, by only typing Nd_theta() into the console.

Regarding your actual question: you can specifiy additional parameters in the following way:

r1 <- 1
r2 <- 1
Nd_theta <- b
integrate(Nd_theta, lower = 0, upper = 10, x = 5)

But notice what the help page to ?integrate says: the first argument of Nd_theta will be used for Integration. so you might need to change the defintion from b <- function(t, x){...} to b <- function(x, t){...}.

Qaswed
  • 3,649
  • 7
  • 27
  • 47