R合并美国县级shapefile与业务数据Polygons ID不匹配报错求解
报错根因排查&修复方案
最常见的3个触发原因
- FIPS字段格式不匹配:Census的原始STATE/COUNTY字段是字符型带前导零,拼接时如果没有强制补全2位州编码、3位县编码,会生成非5位的FIPS值;如果业务表的FIPS存为数值型,会自动丢失前导零,即便你做了交集匹配也可能出现隐形不匹配
- sp对象强制要求行名与多边形ID一一对应:过滤shapefile后,原有多边形ID没有同步更新,和后续合并后的数据框行名无法对应,这是你调用merge方法也没解决的核心原因
- 存在重复FIPS记录:shapefile中存在同FIPS的多段飞地几何,或者业务表中存在同FIPS的重复行,merge后数据行数与多边形数量不匹配
分步修复操作
第一步:校准FIPS字段
library(stringr) # 统一将两边FIPS转为5位字符型,补全前导零 shapefile@data$FIPS <- paste0( str_pad(shapefile@data$STATE, 2, side = "left", pad = "0"), str_pad(shapefile@data$COUNTY, 3, side = "left", pad = "0") ) biz$FIPS <- str_pad(as.character(biz$FIPS), 5, side = "left", pad = "0") # 校验交集数量一致 common_fips <- intersect(shapefile@data$FIPS, biz$FIPS) stopifnot(length(common_fips) == sum(shapefile@data$FIPS %in% common_fips)) stopifnot(length(common_fips) == sum(biz$FIPS %in% common_fips))
第二步:清除重复值
# 分别去重FIPS shapefile <- shapefile[!duplicated(shapefile@data$FIPS), ] biz <- biz[!duplicated(biz$FIPS), ] # 重置shapefile的多边形ID,彻底解决ID不匹配问题 library(sp) shapefile <- spChFIDs(shapefile, as.character(1:nrow(shapefile@data)))
第三步:合并操作
如果继续用sp类对象:
merged_sp <- sp::merge( x = shapefile, y = biz, by = "FIPS", all.x = FALSE, duplicateGeoms = TRUE )
更推荐转sf类规避sp的ID校验问题,后续绘图也更灵活:
library(sf) shape_sf <- st_as_sf(shapefile) merged_sf <- merge(shape_sf, biz, by = "FIPS") # 可转回sp对象兼容旧代码 merged_sp <- as(merged_sf, "Spatial")
内容的提问来源于stack exchange,提问作者Erin
相关产品推荐
相关产品推荐

