【问题标题】:R, sf, st_write, ESRI Shapefile driver, and GDAL optionsR、sf、st_write、ESRI Shapefile 驱动程序和 GDAL 选项
【发布时间】:2021-02-27 22:55:49
【问题描述】:

在R中,我已经成功使用sf包,st_write函数将sf对象写入shapefile,使用ESRI shapefile驱动程序)。我了解st_write 函数依赖于GDAL。

我需要在 df 中编写具有多个 character 类属性的 shapefile。正如预期的那样,这些都是默认的 80 个字符宽度。我需要将这些属性写入更窄的字段宽度。

来自GDAL page:

字段大小驱动程序知道自动扩展字符串和整数字段 (最多由 DBF 格式强加的 255 字节限制)动态 适应要插入的数据的长度。

也可以强制将字段大小调整为最佳 宽度,通过数据源发出 SQL ‘RESIZE’ ExecuteSQL() 方法。这在以下情况下很方便 默认列宽(字符串字段为 80 个字符)大于 必要的。

我需要这样做并强制调整大小,但我不明白如何通过数据源 ExecuteSQL() 方法实现 SQL RESIZE<tablename>。我对 SQL 不流利(或经验丰富),因此不知道从 R 开始。

有人有在 R 中这样做的例子吗?你能指出我正确的方向或提供一个例子吗?

【问题讨论】:

    标签: r gdal sf


    【解决方案1】:

    我想出了解决方案,实际上很简单。使用 st_write 中的 Layer_options

    #load data
    data(meuse,package="sp")
    
    #create a character atribute with 10 characters
    meuse$character<-"0123456789"
    
    #convert to sf
    meuse_sf = st_as_sf(meuse, coords = c("x", "y"), crs = 28992)
    
    #drop extra attributes
    final<-meuse_sf[,"character"]
    
    #original problem, st_write to the esri driver
    #would create a character field of length 80
    st_write(final, paste0(getwd(), "/", "character_long.shp"))
    
    #as per GDAL https://gdal.org/drivers/vector/shapefile.html#vector-shapefile
    #LAYER CREATION OPTIONS
    #RESIZE=YES/NO: set the YES to resize fields to their optimal size. 
    #See above “Field sizes” section. Defaults to NO.
    
    Layer_opt<-c("RESIZE=yes")
    st_write(final,paste0(getwd(), "/", "character_RESIZE.shp"),layer_options = Layer_opt)
    #this writes to a text field optimized to the contents (in this case 10)
    

    后续问题,有没有办法将字段设置为特定长度

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 2021-10-19
      • 2022-08-05
      • 2019-06-09
      • 1970-01-01
      • 2021-12-09
      • 2014-05-16
      • 2017-03-03
      • 1970-01-01
      相关资源
      最近更新 更多