在R中使用Shapefile查找相交图形时结果异常的问题求助
问题分析与修正方案
1. 坐标系不统一(最可能的触发原因)
如果两个shapefile的空间参考(坐标系)不一致,terra::intersect无法正确计算几何交集,大概率会直接返回第一个输入图层(也就是shapefile1)。先检查并统一坐标系:
# 统一用terra包处理,避免跨包类型混乱 library(terra) # 读取矢量文件 shapefile1 <- vect("shapefile1.shp") shapefile2 <- vect("shapefile2.shp") # 查看两个文件的坐标系 crs(shapefile1) crs(shapefile2) # 若坐标系不同,将shapefile2转换为shapefile1的坐标系 if (!identical(crs(shapefile1), crs(shapefile2))) { shapefile2 <- project(shapefile2, crs(shapefile1)) }
2. 跨包类型混用的隐患
你用sf的st_read读取数据得到sf对象,再传入terra函数处理,虽然terra会自动转换,但容易出现隐式错误。建议全程用terra包的函数处理矢量数据,减少类型转换风险。
3. 函数选择需匹配你的实际需求
你的需求是“找出两者中彼此相交的图形”,分两种场景处理:
场景A:提取两个图层几何重叠的区域(即交集多边形)
如果要得到两个图层重叠部分的几何形状,修正后代码:
library(terra) # 读取并统一坐标系 shapefile1 <- vect("shapefile1.shp") shapefile2 <- vect("shapefile2.shp") if (!identical(crs(shapefile1), crs(shapefile2))) { shapefile2 <- project(shapefile2, crs(shapefile1)) } # 计算几何交集 intersecting_regions <- intersect(shapefile1, shapefile2) # 导出结果 writeVector(intersecting_regions, "/Desktop/Allocation/testing12.shp")
场景B:筛选出两个图层中互相有交集的原要素(保留原几何,仅过滤不相交的)
如果要保留shapefile1中与shapefile2相交的所有原要素,以及shapefile2中与shapefile1相交的原要素,用以下代码:
library(terra) shapefile1 <- vect("shapefile1.shp") shapefile2 <- vect("shapefile2.shp") if (!identical(crs(shapefile1), crs(shapefile2))) { shapefile2 <- project(shapefile2, crs(shapefile1)) } # 筛选shapefile1中与shapefile2相交的要素 shape1_intersect <- subset(shapefile1, intersects(shapefile1, shapefile2)) # 筛选shapefile2中与shapefile1相交的要素 shape2_intersect <- subset(shapefile2, intersects(shapefile2, shapefile1)) # 合并两个筛选后的图层(按需选择) combined_intersect <- rbind(shape1_intersect, shape2_intersect) # 导出结果 writeVector(combined_intersect, "/Desktop/Allocation/testing12.shp")
提前验证相交情况
运行代码前,可先确认两个图层的相交状态:
# 统计shapefile1中与shapefile2相交的要素数量 sum(intersects(shapefile1, shapefile2)) # 统计shapefile2中与shapefile1相交的要素数量 sum(intersects(shapefile2, shapefile1))
如果结果为0,说明两个图层无交集;如果结果等于shapefile1的要素总数,说明shapefile1所有要素都被shapefile2覆盖,此时intersect返回的交集会与shapefile1一致。
内容的提问来源于stack exchange,提问作者walle_eva
相关产品推荐
相关产品推荐

