使用bdc_country_from_coordinates函数时遇Loop 0无效错误求解决
解决
bdc_country_from_coordinates()拓扑错误的方案 这个错误是因为地理边界数据存在拓扑瑕疵(重复顶点),而bdc依赖的s2库对地理数据的有效性检查非常严格,哪怕官方示例用的rnaturalearth数据也可能踩这个坑。下面是几个可行的解决办法:
方法1:修复国家边界的拓扑问题
手动加载rnaturalearth的国家边界,用sf包修复拓扑后再传给函数:
library(bdc) library(rnaturalearth) library(sf) # 加载国家边界并修复拓扑错误 world <- ne_countries(returnclass = "sf") world_fixed <- st_make_valid(world) # 调用函数时指定修复后的边界数据 bdc_country_from_coordinates( data = latlong_data, lat = "decimalLatitude", lon = "decimalLongitude", country = "country", world = world_fixed )
方法2:放宽s2的有效性检查
临时关闭s2的严格检查,让它自动处理无效的地理数据:
library(s2) # 开启自动修复无效地理对象的选项 s2_options(s2_geography_force_valid = TRUE) # 再运行你的原代码 library(bdc) library(rnaturalearthdata) library(rnaturalearth) bdc_country_from_coordinates(latlong_data, lat = "decimalLatitude", lon = "decimalLongitude", country = "country")
方法3:换用更可靠的地理数据源
试试高分辨率的边界数据或者其他数据源,比如:
用rnaturalearthhires高分辨率边界
install.packages("rnaturalearthhires") library(rnaturalearthhires) # 加载1:1000万分辨率的国家边界并修复拓扑 world_hires <- ne_countries(scale = 10, returnclass = "sf") world_hires_fixed <- st_make_valid(world_hires) bdc_country_from_coordinates( data = latlong_data, lat = "decimalLatitude", lon = "decimalLongitude", country = "country", world = world_hires_fixed )
用GADMTools的边界数据
install.packages("GADMTools") library(GADMTools) # 加载GADM的国家边界数据 world_gadm <- gadmLoadCountries(level = 0, basefile = "gadm41") world_gadm_sf <- st_as_sf(world_gadm) bdc_country_from_coordinates( data = latlong_data, lat = "decimalLatitude", lon = "decimalLongitude", country = "country", world = world_gadm_sf )
方法4:直接用sf手动实现坐标匹配
如果上述方法都不行,跳过bdc的函数,用sf的空间连接自己做匹配:
library(sf) library(rnaturalearth) # 将你的数据集转成sf地理对象 latlong_sf <- st_as_sf( latlong_data, coords = c("decimalLongitude", "decimalLatitude"), crs = 4326 # WGS84坐标系 ) # 加载并修复国家边界 world <- ne_countries(returnclass = "sf") world_fixed <- st_make_valid(world) # 空间连接匹配对应国家 result <- st_join(latlong_sf, world_fixed[, "name"], join = st_within) # 转回普通数据框(如果不需要地理信息) result_df <- st_drop_geometry(result)
内容的提问来源于stack exchange,提问作者Emmy
相关产品推荐
相关产品推荐

