[R] integration problem

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Tue Oct 26 18:19:36 CEST 2004



Christoph Scherber wrote:
> Dear R users,
> 
> I have spectral data (say, wavelength vs. extinction coefficient) for 
> which I´d like to calculate an integral (i.e. the area underneath the 
> curve).
> 
> Suppose the (artificial) dataset is
> 
> lambda     E
> 1     2
> 2     4
> 3     5
> 4     8
> 5     1
> 6     5
> 7     4
> 8     9
> 9     8
> 10     2
> 
> 
> 
> How can I calculate an integral  for these values using R?
> 
> Many thanks for any help!
> Regards
> 
> Christoph
> 

Hi Christoph,
   You can write some code to do trapezoidal integration or use ?approx 
in the following manner:

f <- function(xnew, x, y) approx(x, y, xnew)$y
integrate(f, min(x$lambda), max(x$lambda), x = x$lambda, y = x$E)

where `x' is your data above. Using approx is perhaps overkill but it 
works. A better solution would be to use trapezoids or perhaps piecewise 
linear integration. I don't know of a package that has the latter 
approaches off the top of my head but that doesn't mean they doesn't 
exist somewhere.

--sundar




More information about the R-help mailing list