在R中导入CMEC动物地理区系shapefile遇错求助
问题背景
尝试导入包含11个生物地理区域的newRealms.shp文件(已放入R工作目录),使用代码:
library(sf) realms <- read_sf("newRealms.shp")
执行后出现错误与警告:
错误:Cannot open [文件路径\newRealms.shp]; The source could be corrupt or not supported. See
st_drivers()for a list of supported formats.
警告:In CPL_read_ogr(dsn, layer, query, as.character(options), quiet, :
GDAL Error 4: Unable to open [文件路径\newRealms.shx] or [文件路径\newRealms.SHX]. Set SHAPE_RESTORE_SHX config option to YES to restore or create it.
同时在RStudio「Files」面板直接点击该文件时,收到提示:"File is binary rather than text so cannot be opened by the source editor."
解决步骤
1. 检查shapefile配套文件
shapefile是一组文件的集合,必须保证.shp、.shx(索引文件)、.dbf(属性表)等核心文件存在于同一目录。先执行以下命令确认工作目录中的相关文件:
list.files(pattern = "newRealms")
2. 启用GDAL修复配置读取文件
利用sf包设置GDAL的SHAPE_RESTORE_SHX选项,让系统自动修复或重建缺失的.shx文件:
library(sf) # 开启缺失.shx文件的修复配置 st_set_options(SHAPE_RESTORE_SHX = "YES") # 重新读取shapefile realms <- read_sf("newRealms.shp")
3. 验证读取结果
读取完成后,可通过以下命令确认数据是否正常:
# 查看数据结构 str(realms) # 快速绘图验证地理数据 plot(realms)
4. 备选方案:重新下载数据集
若上述方法无效,大概率是下载时文件损坏。重新下载完整的数据集压缩包,解压后确保所有配套文件完整,再尝试导入。
内容的提问来源于stack exchange,提问作者Bradley Allf

