You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:在R中用sf包read_sf()读取QGIS可用shp文件失败

问题:R中sf包读取GADM埃及Shapefile失败的排查与解决

我有一个名为gadm41_EGY_1.shp的Shapefile,已在QGIS中成功用于分析,现在希望在R中使用sf包的read_sf()函数将其读取,以进行伪缺失分析并在R Studio的绘图环境中绘制地图。我已手动设置工作目录确保文件路径正确,但三次读取尝试均失败,具体情况如下:

第1次尝试代码

#Install the pacakge sf
install.packages("sf", configure.args = "--with-proj-lib=/usr/local/lib/")

library(sf)

#Set the CRS
crswgs84=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")

#Plot the shape file 
Egypt_Sf<-read_sf("/Users/Documents/gadm41_EGY_1_Shape/gadm41_EGY_1.shp", 
                    proj4string=crswgs84, verbose=TRUE)

错误信息

Error: Cannot open "/Users/Documents/gadm41_EGY_1_Shape/gadm41_EGY_1.shp""; The source could be corrupt or not supported. See `st_drivers()` for a list of supported formats.
In addition: Warning message:
In CPL_read_ogr(dsn, layer, query, as.character(options), quiet,  :
  GDAL Error 4: Unable to open /Users/Documents/gadm41_EGY_1_Shape/gadm41_EGY_1.shp"" or /Users/Documents/gadm41_EGY_1_Shape/gadm41_EGY_1.shp"".SHX. Set SHAPE_RESTORE_SHX config option to YES to restore or create it.

第2次尝试代码

#Define a path to the shapefile 
Ds_sf <- system.file("/Users/Documents/gadm41_EGY_1_Shape/gadm41_EGY_1.shp")
Ds_sf

#Set the CRS
crswgs84=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")

#Read shape file in R
Egypt_Sf<-read_sf(Ds_sf, proj4string=crswgs84, quiet = TRUE, verbose=TRUE)

错误信息

Error: `dsn` must point to a source, not an empty string.

第3次尝试代码

Egypt_Sf <- read_sf(dsn = "/Users/Documents/gadm41_EGY_1_Shape/gadm41_EGY_1.shp", 
                         quiet=TRUE, verbose=TRUE, stringAsFactors=TRUE)

错误信息

Error in st_sf(x, ..., agr = agr, sf_column_name = sf_column_name) : 
  no simple features geometry column present

解决思路与方案

错误原因分析

  1. 第1次尝试:

    • 误用proj4string参数:该参数属于sp包,sf包不支持,read_sf会自动读取Shapefile自带的CRS;若需转换CRS,应使用st_transform()。
    • SHX文件问题:GDAL提示无法读取.shx索引文件,需启用GDAL的SHAPE_RESTORE_SHX参数修复。
  2. 第2次尝试:

    • system.file()函数用途错误:该函数用于查找R包内置文件路径,不能指定本地用户文件,导致Ds_sf返回空字符串,触发dsn为空的错误。
  3. 第3次尝试:

    • 核心问题仍为SHX文件读取异常,导致无法识别几何列;同时stringAsFactors参数在新版R中已默认无效,无需设置。

正确操作步骤

  1. 确认Shapefile的所有附属文件(.shp、.shx、.dbf、.prj等)均在同一文件夹下(QGIS能打开说明文件本身有效,仅索引文件读取异常)。
  2. 使用以下代码读取文件:
# 加载sf包
library(sf)

# 设置GDAL参数,自动修复SHX索引文件
st_set_option("SHAPE_RESTORE_SHX", "YES")

# 读取Shapefile(推荐直接指定文件夹路径,sf会自动识别图层)
Egypt_Sf <- read_sf(dsn = "/Users/Documents/gadm41_EGY_1_Shape/")

# 查看数据结构
head(Egypt_Sf)

# 若需转换CRS到WGS84(EPSG:4326),执行以下代码
# Egypt_Sf <- st_transform(Egypt_Sf, crs = 4326)

# 绘制地图
plot(st_geometry(Egypt_Sf))

补充说明

  • 若已设置工作目录为Shapefile所在文件夹,可直接使用相对路径:read_sf("gadm41_EGY_1.shp")。
  • 新版sf默认使用S2球面几何,若遇兼容性问题,可执行sf_use_s2(FALSE)切换回平面几何。

内容的提问来源于stack exchange,提问作者Alice Hobbs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 12:44:57