Integral Function in R

10,368

This should work:

# Function
f=function(s,a,lambda){
   1-exp(-integrate(lambda,lower=a,upper=s,rel.tol=1e-5)$value)   
}

# Check
f(s=1,a=0,lambda=function(t) t)
1-exp(-1/2)

Some important warnings:

1) integrate needs a vectorized function to work with, you will need to adapt your lambdafunction to satisfy this constraint (for example by using lambda.vect=function(t) sapply(t,function(tt) lambda(tt))). Recall what happens here:

f(s=1:2,a=0,lambda=function(t) 1) # Use rep(1,length(t)) instead

2) If the function $\lambda$ is too wiggly then you may need to tune the arguments subdivisions and abs.tol appropiately, see the documentation.

3) f is not a vectorized function, so it will return a single value no matter if you pass an vector to s. To vectorize it, adapt solution on 1).

Share:
10,368
g_puffo
Author by

g_puffo

Updated on June 14, 2022

Comments

  • g_puffo
    g_puffo almost 2 years

    I have defined the following function in R

    enter image description here

    (where a is a given constant and enter image description here is a known function) but when I try to compute the values of it I get some pretty weird numbers.

    I should point out that, in order to compute the values of f(s), I have actually solved the integral analytically before hand hence, in reality, my user defined function in R doesn't have to compute that integral. I would like to see whether I have made a mistake in my R code (since I'm pretty sure I solved the integral correctly) by comparing my values with those I would get If I were to solve the integral numerically. I have read the documentation for integrate but it doesn't seem to do what I need: am I correct? Can anybody point me in the right direction?