Eka - 1 year ago 111
R Question

# How to find whole distance between two points in a curved line in R?

I have a similar line graph plotted using R plot function (

plot(df)
)

I want to get distance of the whole line between two points in the graph (e.g., between x(1) and x(3)). How can I do this?

1. If your function is defined over a fine grid of points, you can compute the length of the line segment between each pair of points and add them. Pythagoras is your friend here:

To the extent that the points are not close enough together that the function is essentially linear between the points, it will tend to (generally only slightly) underestimate the arc length.

Note that if your x-values are stored in increasing order, these $\delta_x$ and $\delta_y$ values can be obtained directly by differencing (in R that's diff)

2. If you have a functional form for $y$ as a function of $x$ you can apply the integral for the arc length:

$$s=\int _{a}^{b}{\sqrt {1+\left({\frac {dy}{dx}}\right)^{2}}}dx;$$

this is essentially just the calculation in 1 taken to the limit.

3. If both $x$ and $y$ are parametric functions of another variable ($t$, say) you can simplify the parametric form of the above integral (if we don't forget the Jacobian) to

$$s=\int _{a}^{b}{\sqrt {\left({\frac {dx}{dt}}+{\frac {dy}{dt}}\right)^{2}}}dt.$$

(Note the direct parallel to 1.)

4. if you don't have a convenient-to-integrate functional form in 2. or 3. you can use numerical quadrature; this can be quite efficient (which can be handy when the derivative function is expensive to evaluate).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download