R、sf、st_write、ESRI Shapefile驱动程序和GDAL选项

3
在R中,我成功地使用了sf包和st_write函数将sf对象写入shapefile(使用ESRI shapefile驱动程序)。我知道st_write函数依赖于GDAL。
我需要用character类属性在df中写入shapefiles。这些都按预期以默认的80个字符宽度进行编写。我需要将这些属性写入更窄的字段宽度。
GDAL页面得知:
字段大小 驱动程序知道如何自动扩展字符串和整数字段(最多255个字节,受DBF格式的限制),以动态适应要插入的数据长度。
还可以通过数据源ExecuteSQL()方法发出SQL“RESIZE”来强制调整字段到最佳宽度。在默认列宽(字符串字段为80个字符)比必要的宽时,这很方便。
我需要做的就是强制调整大小,但我不知道如何通过数据源ExecuteSQL()方法实现SQL RESIZE<tablename>。我不熟练(或有经验)SQL,因此不知道从哪里开始在R中操作。
是否有人有在R中执行此操作的示例?您能指导我正确的方向或提供一个示例吗?
1个回答

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)

跟进问题,有没有办法将字段设置为特定长度?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接