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
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
Hi Christoph I use this function to calculate an area under curve. It integrates along the whole wavelength set or you can restrict the calculation by setting dm and hm to some appropriate values. It also gives you two values. The first is total area to the x axis (y=0) and the second is only area below the curve and above line from min(x) to max(x). integ1<-function (x,y,dm=-Inf,hm=+Inf) { if(dm==-Inf)dm<-min(x) if(hm==+Inf)hm<-max(x) vyber<-x<=hm&x>=dm l<-length(x[vyber]) v<-diff(x[vyber]) z<-y[vyber][1:l-1]+y[vyber][2:l] o<-z*v/2 osum<-sum(o) o1<- (y[x==min(x[vyber])]+y[x==max(x[vyber])])*(max(x[vyber])- min(x[vyber]))/2 cista<-osum-o1 return(c(osum,cista)) } I have also a function for specifying region for integration from plotted picture, if you are interested. Cheers Petr On 26 Oct 2004 at 17:54, 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 > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! > http://www.R-project.org/posting-guide.htmlPetr Pikal petr.pikal at precheza.cz