Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing integral of a line plot in R

Tags:

plot

r

integral

I have two positive-valued vectors x,y of the same length in R. Using plot(x, y, "l",...), gives me a continuous line plot in 2 dimensions out of my finite vectors x and y. Is there a way to compute a definite integral over some range of this line plot in R?

edit1: I've looked into the integrate function in R. I'm not sure however how to make a function out of two vectors to pass to it, as my vectors are both finite.

edit2: For some more background, The length of x and y ~ 10,000. I've written a function to find periods, [xi, xj], of abnormalities in the data I'm observing. For each of these abnormalities, I've used plot to see what's going on in these snippets of my data. Now i need to compute statistics concerning the values of the integrals in these abnormal periods, so I'm trying to get as accurate as a number as possible to match with my graphs. X is a time variable, and I've taken very fine intervals of time.

like image 827
mt88 Avatar asked Jan 28 '26 17:01

mt88


1 Answers

You can do the integration with integrate(). To create a function out of your vectors x and y, you need to interpolate between the values. approxfun() does exactly that.

integrate takes a function and two bounds.

approxfun takes two vectors x and y just like those you have.

So my solution would be :

integrate(approxfun(x,y), range(x)[1], range(x)[2])
like image 156
kjaquier Avatar answered Jan 30 '26 09:01

kjaquier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!