You need to enable JavaScript to run this app. 使用st_write导出st_union生成的sf对象出现CPL_write_ogr错误
优惠活动
大模型
产品
解决方案
定价
更多

使用st_write导出st_union生成的sf对象出现CPL_write_ogr错误

问题解决指南

错误根因

  • 直接调用st_union()合并两个sf对象,输出结果为sfc纯几何序列,并非带标准sf对象结构的数据集,写入shapefile时会缺失属性表结构,导致文件写入不完整、读取后无法被tmap识别。
  • Windows系统下路径使用单反斜杠\为R的转义字符,存在路径识别异常的可能。

修复代码

library(sf)
library(tmap)

# 读取原始数据,路径改用正斜杠规避转义问题
Montenegro <- st_read("z:/NTU/master research/GIS data/World_Countres_WGS84/Supplementary_Countries/Montenegro/MNE_adm0.shp")
Serbia <- st_read("z:/NTU/master research/GIS data/World_Countres_WGS84/Supplementary_Countries/Serbia/SRB_adm0.shp")

# 合并几何后转为标准sf对象
Serbia.Montenegro <- st_union(Montenegro, Serbia) |> st_sf()

# 写入时增加delete_layer参数,避免目标路径已有文件导致的写入冲突
st_write(
  Serbia.Montenegro, 
  "z:/NTU/master research/GIS data/World_Countres_WGS84/Supplementary_Countries/Serbia and Montenegro/SerAndMon.shp",
  delete_layer = TRUE
)

# 验证读取与绘图
test <- st_read("z:/NTU/master research/GIS data/World_Countres_WGS84/Supplementary_Countries/Serbia and Montenegro/SerAndMon.shp")
qtm(test)

可选优化

如果需要保留原有国家的属性字段,可先对两个sf做行合并后再执行联合:

# 仅保留两个数据集共有的属性字段后合并,再做联合
Serbia.Montenegro <- rbind(
  Montenegro[, c("NAME_EN", "ISO3")], # 替换为你需要保留的共有的字段名
  Serbia[, c("NAME_EN", "ISO3")]
) |> 
  st_union(by_feature = FALSE) |> 
  st_sf()

内容的提问来源于stack exchange,提问作者Polly Wu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 05:09:03