6

使用sfR 中的包,我正在读取存储在地理包中的一系列层,过滤它们,然后将它们重新保存为新的地理包。
当我设置我的脚本时,我测试了其中一个层并且它工作正常,但是当在层列表上运行相同的代码时,它失败了,因为测试层已经存在。的文档st_write同时具有附加和覆盖参数,但设置为替换而不是附加(append = FALSEoverwrite = TRUE)会导致它失败并出现错误

st_write.sf (., dsn = gpkg_out, layer = layername, overwrite = TRUE) 中的错误:无法识别的参数覆盖

st_write.sf(., dsn = gpkg_out, layer = layername, append = FALSE) 中的错误:无法识别的参数追加

我更新了我的 sf 包副本,但它仍然失败并出现同样的错误。我通过删除文件系统中的文件找到了解决方法,但是如果我只是尝试替换一层,这将是有问题的。

有谁知道这是否是一个已知问题或一种使其替换而不是附加图层的方法?

我的代码:

library(sf)
library(tidyverse)

gpkg <- "D:/GIS/Sugar/SugarEC_hydropts.gpkg"  # name of existing geopackage

layers = st_layers(gpkg)$name
layers
# [1] "ec1520"  "ec17200" "ec224"   "ec2500" 
#  "ec271"   "ec4680"  "ec488"   "ec5540"  "ec8140"  "ec9860" 

gpkg_out <- "D:/GIS/Sugar/SugarEC_hydropts_wet.gpkg"

# the following works, but appends to layer if it exists
read_write <-  function (layername) {
      st_read(gpkg, layer = layername ) %>%
      filter(Water_Elev_ft >0) %>%
      st_write(dsn = gpkg_out, layer = layername)  # Appends
#   
#   This following versions fails though:
#     st_write(dsn = gpkg_out, layer = layername, overwrite = TRUE) 
#   or
#     st_write(dsn = gpkg_out, layer = layername, append = FALSE)

      invisible()
}

lapply(layers, read_write)
4

2 回答 2

6

delete_dsn = TRUE如果数据可能已经存在,您似乎需要使用。如果数据尚不存在,将引发警告,但仍将写入文件。

nc <-  read_sf(system.file("shape/nc.shp", package="sf"))

Reading layer `nc' from data source `/home/mrhellmann/R/x86_64-pc-linux-gnu-library/3.6/sf/shape/nc.shp' using driver `ESRI Shapefile'
Simple feature collection with 100 features and 14 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
epsg (SRID):    4267
proj4string:    +proj=longlat +datum=NAD27 +no_defs


st_write(nc, 'nc_test.shp', 'nc')

Writing layer `nc' to data source `nc_test.shp' using driver `ESRI Shapefile'
Writing 100 features with 14 fields and geometry type Multi Polygon.

## Error here, as it already exists.
st_write(nc, 'nc_test.shp', 'nc')

Dataset nc_test.shp already exists: remove first, use update=TRUE to append,
delete_layer=TRUE to delete layer, or delete_dsn=TRUE to remove the entire data source before writing.
Error in CPL_write_ogr(obj, dsn, layer, driver, as.character(dataset_options),  : 
  Dataset already exists.


# No error when delete_dsn = T
st_write(nc, 'nc_test.shp', 'nc', delete_dsn = T)

Deleting source `nc_test.shp' using driver `ESRI Shapefile'
Writing layer `nc' to data source `nc_test.shp' using driver `ESRI Shapefile'
Writing 100 features with 14 fields and geometry type Multi Polygon.


nc_saved <- read_sf('nc_test.shp')

identical(nc, nc_saved)
#[1] TRUE


于 2020-01-06T22:28:44.193 回答
3

用于delete_layer = TRUE覆盖/更新 GeoPackage 或 shapefile 中的图层。

于 2021-01-21T23:05:40.170 回答