sf
包中的st_intersects
函数。以下是一个示例,使用北卡罗来纳州的三个县作为多边形。
加载sf
:
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.2, PROJ 6.2.1
制作多边形数据(免责声明:为了快速说明地理经度,纬度坐标在这里被使用,但实际上应该使用平面投影坐标):
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])
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(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)
查找交集:
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