I am working on a problem where I identify approximately parallel lines. From the two lines that I have deemed parallel, I want to calculate the length of the segment that has a shared domain or range, or both domain and range.
In these examples I am using truly parallel lines for sake of simplicity.
There are four scenarios that we have to solve for: positive slope, negative slope, no slope, and undefined slopes.
Helper functions:
Code
# calculate range of x values x_range<-function(x){bbox<-sf::st_bbox(x)return(c(bbox$xmin, bbox$xmax))}# calculate range of y values y_range<-function(x){bbox<-sf::st_bbox(x)return(c(bbox$ymin, bbox$ymax))}# calculate overlapping range between two rangesoverlap_range<-function(r1, r2){if(r1[2]<r2[1]||r2[2]<r1[1]){return(NA)}else{return(c(max(r1[1], r2[1]), min(r1[2], r2[2])))}}find_overlaps<-function(a, b){list( x_overlap =overlap_range(x_range(a), x_range(b)), y_overlap =overlap_range(y_range(a), y_range(b)))}overlap_rect<-function(x){bbox<-sf::st_bbox(c( xmin =x$x_overlap[1], xmax =x$x_overlap[2], ymin =x$y_overlap[1], ymax =x$y_overlap[2]))sf::st_as_sfc(bbox)}
Positive Slope
The first scenario is the shared positive slope.
Question:
How do I find the coordinates of the contained line segment to calculate the length? The solution should be able to handle the scenario where x and y are flipped as well.
We can see that these two lines are parallel. We find their overlapping range:
overlap<-find_overlaps(x[1], x[2])overlap
$x_overlap
[1] 0.5 2.0
$y_overlap
[1] 0.75 2.00
What we want to calculate is the length of the red line segment contained by the bounding box.
plot(x, col =c("red", "black"))plot(overlap_rect(overlap), add =TRUE)
Negative Slope Scenario
We have a very similar scenario. But this time with a negative slope. The solution should be able to handle if I want to find each line segment if x and y are swapped.