9

I'm trying to write multiple layers to the same GeoPackage in R, but I get an error, Creation of output file failed. I have tried to search for documentation of reading and writing to .gpkg files with RGDAL, e.g. to figure out whether writeOGR() actually supports multiple layers, with little success. Is this even possible, if so, how to do it? Minimal working example:

library(sp)
library(maptools)
library(rgdal)

data(wrld_simpl)

norway <- wrld_simpl[wrld_simpl$NAME == "Norway", ]
sweden <- wrld_simpl[wrld_simpl$NAME == "Sweden", ]

file <- tempfile("scandinavia", fileext = c(".gpkg"))

writeOGR(norway, dsn = file, layer = "norway", driver = "GPKG")
writeOGR(sweden, dsn = file, layer = "sweden", driver = "GPKG")

ogrListLayers(file)

There is apparently an ogr2ogr shell command that does the trick (hat tip mdsumner), which I can wrap in an R function. However, it would be neat if writeOGR() and/or st_write() in the sf package had this built in. I reckon it depends on GDAL's layer_options, but there doesn't seem to be an append-type option for GPKG in GDAL.


I could write a simple wrapper function for st_write() but native support in sf or rgdal would be better.

  • Not possible afaik. Try with sf, which I will be happy to explore as well - it's easier to fix than rgdal for one thing – mdsumner Jan 4 '17 at 21:21
  • 1
    @mdsumner st_write() in sf gives the same result. I think the lack of an append option in GDAL's layer creation options is the source of the problem for both writeOGR() and st_write(). – eivindhammers Jan 5 '17 at 9:32
6

You can do this using the update flag on sf::st_write:

library(sf)

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

st_write(nc,     "nc.gpkg", "nc")
st_write(storms, "nc.gpkg", "storms", update = TRUE)

st_layers("nc.gpkg")

Driver: GPKG

Available layers:

layer_name geometry_type features fields

1 nc Multi Polygon 100 14

2 storms 3D Line String 71 0

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.