# calculate the length of a line under a curve

X = 0, 1, 2, 3, 4, 5
Y = 77, 62, 55, 67, 43, 88
I plan to draw a spline curve with this data, and calculate the length of lines truncated by the curve when y = 65.
Or just like the pic below, i would like to know the length of AB+CD.

Something like that could find the crossings coordinates, then you have to subtract/add to get the distances (you can use the fact that the sign of `crossings` gives you the crossing direction).

``````X = c(0, 1, 2, 3, 4, 5)
Y = c(77, 62, 55, 67, 43, 88)

spl <- splinefun(X,Y)

new_x <- (1:5000)/100
new_y <- spl(new_x)

crossings <- diff(sign(new_y - 65))
x_crossings <- new_x[which(crossings != 0)]

plot(X,Y)
lines(new_x, new_y, col='red')
abline(h=65,col="grey",lty="dashed")
for(xc in x_crossings){
abline(v = xc, col="green4", lty="dotted")
}
`````` Created on 2021-11-14 by the reprex package (v2.0.1)

There might be a better way to find x for a given y, rather than computing the value at a bunch of points; I think there are `findZeros()` functions in several packages, not sure if they'll give you the sign of the crossing (if it's really a concern, you might be able to use `spl(x, deriv=1)`).

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.