mt88
mt88

Reputation: 3015

Computing integral of a line plot in R

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.

Upvotes: 3

Views: 5394

Answers (3)

Alban K
Alban K

Reputation: 51

I landed here much later. But for future visitors, here is some code for the suggestion from
Greg Snow's answer, for piece-wise linear functions:

line_integral <- function(x, y) {
dx <- diff(x)
  end <- length(y)
  my <- (y[1:(end - 1)] + y[2:end]) / 2
  sum(dx *my)
} 

# example
x <- c(0, 2, 3, 4, 5, 5, 6)
y <- c(0, 0, 1,-2,-1, 0, 0)
plot(x,y,"l")
line_integral(x,y)

Upvotes: 1

kjaquier
kjaquier

Reputation: 854

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])

Upvotes: 5

Greg Snow
Greg Snow

Reputation: 49640

The approxfun function will take 2 vectors and return a function that gives the linear interpolation between the points. This can then be passed to functions like integrate. The splinefun function will also do interpolation, but based on a spline rather than piecewise linear.

In the piecewise linear case the integral will just be the sum of the trapezoids, it may be faster/simpler to just sum the areas of the trapezoids (the width, difference in x's

Upvotes: 3

Related Questions