After making some changes to an sp object I want to save it as a shapefile using writeOGR()so that I don't have to repeat the cleaning every time.

I haven't found a way to identify the layer name of the sp object though.

boundaries <- geojson_read("http://geoportal.statistics.gov.uk/datasets/8edafbe3276d4b56aec60991cbddda50_2.geojson", what = "sp")

# irrevelant data cleaning steps

writeOGR(obj = boundaries, dsn = "tempdir", layer = "??????", driver = "ESRI Shapefile", verbose = TRUE)

I'm hesitant to use sf instead because of the need to work with some existing code that all relies on sp. But maybe it's time to rewrite that stuff.

1 Answer 1


For shapefile it has to be the name of the file without extension, so whatever you nominate as layer will be the file name, if you try to separate these by giving an explicit filename in dsn then the layer will be ignored.

u <- "http://geoportal.statistics.gov.uk/datasets/8edafbe3276d4b56aec60991cbddda50_2.geojson"
d <- rgdal::readOGR(u)
rgdal::writeOGR(d, dsn = ".", layer = "somelayer", driver = "ESRI Shapefile")
list.files(pattern = "shp$")
[1] "somelayer.shp"

rgdal tells me it's simply the name of the file without extension:


[1] "8edafbe3276d4b56aec60991cbddda50_2"
[1] "GeoJSON"
[1] 1

As does sf

Driver: GeoJSON 
Available layers:
                      layer_name geometry_type features fields
1 8edafbe3276d4b56aec60991cbddda50_2                    380      6

and vapour

[1] "8edafbe3276d4b56aec60991cbddda50_2"

and GDAL at the command line

system(sprintf("ogrinfo %s ", u))

INFO: Open of `http://geoportal.statistics.gov.uk/datasets/8edafbe3276d4b56aec60991cbddda50_2.geojson'
  using driver `GeoJSON' successful.
1: 8edafbe3276d4b56aec60991cbddda50_2

For GeoJSON, it can be more complicated, since you can nominate your own layer name independently of the file name.

rgdal::writeOGR(d, "file.geojson", "layername", "GeoJSON")
[1] "layername"
[1] "GeoJSON"
[1] 1 

Older versions of GDAL had a generic name, the new logic is described here:

Starting with GDAL 2.2, the layer name is built with the following logic:

If a "name" member is found at the FeatureCollection level, it is used. Otherwise if the filename is regular (ie not a URL with query parameters), then the filename without extension and path is used as the layer name. Otherwise OGRGeoJSON is used.

  • awesome, rgdal::ListLayers() was what I was looking for i guess. Should I be looking to use geojson instead of shapefiles whenever possible? Mar 28, 2019 at 21:23
  • I think both are bad formats, I'd never create GeoJSON unless I had to and the same goes for shapefiles. I use GeoPackage or MapInfo formats, but it totally depends what you need to do!
    – mdsumner
    Mar 28, 2019 at 23:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.