[GIS] Writing multiple layers to GeoPackage using writeOGR() in R

gdalgeopackagerrgdalsf

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.

Best Answer

You can do this using the append 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", append = 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
Related Question