我有2个SHP文件,一个有许多字符串(铁路),另一个有许多多边形(美国的县).这两个文件之间根本没有交集.我的目标是将线捕捉到最近的多边形边界,以便进行交叉并计算每个多边形中线的长度.
我try 使用sf
包中的st_snap
来实现这一目标,但没有得到预期的结果.
这让我在一些简单的数据上判断这个函数,并得到了这些结果:
library(dplyr)
library(tidyverse)
library(sf)
library(units)
library(ggplot2)
poly = st_polygon(list(cbind(c(0, 0, 1, 1, 0), c(0, 1, 1, 0, 0))))
lines = st_multilinestring(list(
cbind(c(0, 1), c(1.01, 1.05)),
cbind(c(0, 1), c(-0.01, -.05)),
cbind(c(1.025, 1.05, 1.025), c(1.05, .5, -.05))
))
t <- st_intersection(poly, lines)
st_is_empty(t)
# [1] TRUE
ggplot()+
geom_sf(data = lines, col = "green")+
geom_sf(data = poly, col = "red", fill = NA)
拍照后我的预期结果是:
但我得到的是:
为tolerance=0.5
snapped1 = st_snap(lines, poly, tolerance=0.5)
print(snapped1)
# MULTILINESTRING ((0 1, 1 1), (0 0, 1 0), (1 1, 1.05 0.5, 1 0))
ggplot()+
geom_sf(data = lines, col = "green")+
geom_sf(data = poly, col = "red", fill = NA)+
geom_sf(data = snapped1, col = "blue", alpha = 0.5)
为tolerance=1.005
snapped2 = st_snap(lines, poly, tolerance=1.005)
print(snapped2)
# MULTILINESTRING ((1 1, 0 1, 0 0, 1 0), (0 1, 1 1, 1 0, 0 0), (0 1, 1 1, 1.05 0.5, 1 0, 0 0))
其中包含预期结果:(0 1, 1 1, 1 0, 0 0)
,但也包含不需要的行.
ggplot()+
geom_sf(data = lines, col = "green")+
geom_sf(data = poly, col = "red", fill = NA)+
geom_sf(data = snapped2, col = "blue", alpha = 0.5)
为tolerance=1.1
snapped3 = st_snap(lines, poly, tolerance=1.1)
print(snapped3)
# MULTILINESTRING ((1 1, 0 1, 0 0, 1 0), (0 1, 1 1, 1 0, 0 0), (1 1, 1 0, 0 0, 0 1))
其中还包含预期结果:(0 1, 1 1, 1 0, 0 0)
,但也包含不需要的行.
ggplot()+
geom_sf(data = lines, col = "green")+
geom_sf(data = poly, col = "red", fill = NA)+
geom_sf(data = snapped3, col = "blue", alpha = 0.5)
对于任何更大的容忍度,结果与第三个相同. 显然,我对这个功能的工作方式有些不理解.我试图查看文档,但找不到任何有用的东西.我很感激对此有任何见解,以及如何通过该功能或其他功能获得我的预期结果.
谢谢.