Reputation: 55
I have a dataset that has 1,000's of lines that I can overlay on a section land map (Sec, Township, Range). I need to identify and collect the names of sections that have which lines crossing them.
I am able to find a single point in a polygon but not a line. The line can traverses multiple sections. I think I need a loop to do this but I am having trouble with it.
I have an example that might help describe what I am trying to achieve.
Any help would be greatly apprecieated!
Upvotes: 3
Views: 2570
Reputation: 4507
If you have your polygons and lines in a standard format you can use st_intersects
from the sf
package. Below is an example using three counties of North Carolina as
polygons.
Load sf
:
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.2, PROJ 6.2.1
Make polygonal data (disclaimer: for quick illustration geographical longitude,latitude coordinates are used here, but really planar projected coordinates should be used):
nc <- st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)
n <- 3
poly_dat <- st_sf(poly_id = LETTERS[1:n], nc$geometry[1:n])
Make line data:
line1 <- st_linestring(rbind(c(-81.8,36.5),c(-80.5,36.5)))
line2 <- st_linestring(rbind(c(-81,36.3),c(-80.5,36.3)))
line_dat <- st_sf(linename = c("1", "2"), geometry = st_sfc(line1, line2, crs = st_crs(poly_dat)))
Plot:
plot(poly_dat, reset = FALSE)
plot(line_dat, add = TRUE, col = 1:2, lty = 2)
legend("topright", legend = paste("Line", 1:2), col = 1:2, lty = 2)
Find intersections:
st_intersects(line_dat, poly_dat)
#> although coordinates are longitude/latitude, st_intersects assumes that they are planar
#> Sparse geometry binary predicate list of length 2, where the predicate was `intersects'
#> 1: 1, 2, 3
#> 2: 3
Upvotes: 4