Home > other >  How can I draw a line from a point to a polygon edge and then get the line's length in sf in R?
How can I draw a line from a point to a polygon edge and then get the line's length in sf in R?

Time:02-24

There are some other posts out there related to this one, such as these: progress so far

But now I can't figure out how to use st_intersection or any such function to figure out where the intersection points are. Most of the trouble lies, I think, in the fact that what I'm creating is not an sf object, and I can't figure out how to get it to be one. I assume that, if I could figure out where the segments intersect the polygon (or the most-northern time they do so, ideally), I could somehow measure from the intersection points to the sampling points using a function like st_distance. Since lake polygons are often really complex, though, it's possible a segment will intersect the polygon multiple times (such as if there is a peninsula south of a given point), in which case I figure I can find the "furthest north" intersection point for each sampling point and use that or else take the minimum such distance for each sampling point.

Anyhow, if someone can show me the couple of steps I'm missing, that'd be great! I feel like I'm so close and yet so far...

CodePudding user response:

Consider this approach, loosely inspired by my earlier post about enter image description here

# now here's the action!!!

for (i in seq_along(cities$name)) {
  
  # create a working linestring object
  wrk_line <- st_coordinates(cities[i, ]) %>% 
    rbind(c(0, -90)) %>% # hello, Mr. Amundsen!
    st_linestring() %>% 
    st_sfc(crs = 4326) %>% 
    st_intersection(shape)
  
  # a single observation
  line_data <- data.frame(
    name = cities$name[i],
    length = st_length(wrk_line),
    geometry = wrk_line
  )
  
  # bind results rows to a single object
  if (i == 1) {
    res <- line_data
    
  } else {
    res <- dplyr::bind_rows(res, line_data)
    
  } # /if - saving results
  
  
} # /for

# finalize results
res <- sf::st_as_sf(res, crs = 4326) 
  

# a quick overview of the lines
ggplot()  
  geom_sf(data = shape)   # polygon of North Carolina
  geom_sf(data = res, color = "red") # 3 lines

enter image description here

# print the results
res
# Simple feature collection with 3 features and 2 fields
# Geometry type: LINESTRING
# Dimension:     XY
# Bounding box:  xmin: -79.81944 ymin: 33.92945 xmax: -77.91222 ymax: 36.08
# Geodetic CRS:  WGS 84
#         name        length                       geometry
# 1    Raleigh 204289.21 [m] LINESTRING (-78.63333 35.76...
# 2 Greensboro 141552.67 [m] LINESTRING (-79.81944 36.08...
# 3 Wilmington  17566.55 [m] LINESTRING (-77.91222 34.22...
  • Related