I have sf features that I have created/manipulated in R that I need to export to shapefile (my client only accepts shapefile format so I cannot use .gpkg or other formats). I have used st_write to successfully save the features as a new file, however, the length of each attribute is the maximum length possible. How can I set the length for each attribute? The help file indicates that this is probably possible but I can't quite figure out how. I'm guessing that is it is in dataset_options = NULL, layer_options = NULL.

Example using sample dataset

nc <- st_read(system.file("shape/nc.shp", package="sf"))
st_write(nc[,c("AREA", "NAME", "CNTY_ID")], "nc_test2.shp",name=c("area", "name", "ID"))

enter image description here

All the numbers are considered as float/double values with the maximum length and precision and the text values have a length of 80. How can I set the length when doing the export? In SQL, the statement would be something like this:

        AREA numeric(5, 3), 
        CNTY_ID int(5))
  • If you can control this it will be via options in GDAL's SHP driver, or other workarounds: gdal.org/drv_shapefile.html . Another option is to (re)write the DBF with foreign::write.dbf which has a max_nchar arg. You probably can't control the numeric type other than double/integer because R has no 'single' floating point type. – mdsumner Apr 10 '19 at 21:38
  • I'm getting deja-vu here - did someone ask this question recently (in the last month or so) - maybe it was for sp and rgdal rather than sf but possibly some insights there too... – Spacedman Apr 11 '19 at 7:10
  • I am still hoping for an answer to this. @mdsumner Could you expand on your answer? I can't see how to use write dbf with different maximum characters for each column/attribute. – user3386170 Aug 19 '19 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.