The function is an interface with the OGR abstraction library for spatial vector data, allowing data to be written out using supported drivers. The drivers supported will depend on the local installation, and the capabilities of those drivers (many are read-only). The objects exported are SpatialPointsDataFrame, SpatialLinesDataFrame, or SpatialPolygonsDataFrame objects as defined in the sp package.

writeOGR(obj, dsn, layer, driver, dataset_options = NULL,
 layer_options=NULL, verbose = FALSE, check_exists=NULL,
 overwrite_layer=FALSE, delete_dsn=FALSE, morphToESRI=NULL,
 encoding=NULL, shp_edge_case_fix=FALSE, dumpSRS = FALSE)

Arguments

obj

a SpatialPointsDataFrame, SpatialLinesDataFrame, or a SpatialPolygonsDataFrame object.

dsn

data source name (interpretation varies by driver --- for some drivers, dsn is a file name, but may also be a folder)

layer

layer name (varies by driver, may be a file name without extension)

driver

a character string equal to one of the driver names returned by ogrDrivers

dataset_options

a character vector of options, which vary by driver, and should be treated as experimental

layer_options

a character vector of options, which vary by driver, and should be treated as experimental

verbose

if TRUE, returns a list of information about the attempted write operation

check_exists

default NULL, which tests for the GDAL version, and sets FALSE if < 1.8.0, or TRUE for >= 1.8.0

overwrite_layer

default FALSE, if TRUE and check_exists=TRUE, delete the existing layer of the same name from the data source before writing the new layer; this will delete data and must be used with extreme caution, its behaviour varies between drivers, and accommodates changes that may appear in GDAL 1.8

delete_dsn

default FALSE, may be set to TRUE if overwrite_layer reports that the data source cannot be updated; this will delete data and must be used with extreme caution, its behaviour varies between drivers, and accommodates changes that may appear in GDAL 1.8

morphToESRI

default NULL, in which case set TRUE if driver is “ESRI Shapefile” or FALSE otherwise; may be used to override this default

encoding

default NULL, if set to a character string, it will be used to convert output strings from the given value to UTF-8 encoding.

shp_edge_case_fix

default FALSE, if TRUE, attempt to work around MULTIPOLYGON to POLYGON degradation in ESRI Shapefile output with two touching exterior rings in a single feature (not yet implemented).

dumpSRS

dump SRS to stdout from inside GDAL to debug conversion - developer use only

Details

Working out which combination of dsn, layer, and driver (and option) values give the desired output takes time and care, and is constrained by the ability of drivers to write output; many are read-only. Use of the references given is highly advisable, with searches in the archives of other software using GDAL/OGR. Note that for the “ESRI Shapefile” driver and GDAL >= 1.9, the layer_options value of ‘ENCODING=“LDID/CP1252”’ or other values found on http://www.autopark.ru/ASBProgrammerGuide/dbfstruc.htm to set the encoding byte of the output DBF file (link refered to in ogr/ogrsf_frmts/shape/ogrshapelayer.cpp. The effect of setting the LDID may vary depending on whether GDAL is built with iconv or not, and on the setting of the CPL Option “SHAPE_ENCODING”.

While there is no certainty, newer drivers such as KML, GML, SQLite and Geopackage (GPKG) may encode string fields as UTF-8. Users are advised to explore this on a case to case basis using Encoding on string fields of objects to be output, converting where necessary with iconv or assigning the appropriate value with Encoding.

Value

if verbose=TRUE, a list of information about the attempted write operation

Note

Only a subset of possible data slot column classes may be written out; if the function returns an error that the data type of stated columns is unknown, examine the classes and check that they are one of c("numeric", "character", "factor", "POSIXt", "integer", "logical"), and if not convert to such classes. Classes c("factor", "POSIXt") are converted to character strings, and c("logical") to integer internally.

For writing with the KML and GPX drivers, note that the geometries should be in geographical coordinates with datum WGS84.

Warning

The overwrite_layer and delete_dsn arguments are provided only for experienced script writers who need to be able to destroy data, for example during repetetive simulation runs. They should never be used by anyone who is not confident about deleting files.

writeOGR Polygon bug in 1.1-1

In fixing a bug in the correct handling of SFS polygon geometries in version 1.1-1, a further bug was introduced affecting cases of wkbPolygon (not wkbMultiPolygon) output where SFS hole status in the output object was (correctly) defined in the comment to Polygons objects. The error only occurred when all the Polygons objects had one exterior ring, and zero or more interior rings. The error led to the coordinates of the rings cumulating, because the rings were not emptied before assigning the next ring. Version 1.1-2 corrects the error; thanks to JamesWorrall for a complete bug report https://stat.ethz.ch/pipermail/r-sig-geo/2015-December/023796.html.

References

https://gdal.org/drivers/vector/index.html, https://resources.oreilly.com/examples/9780596008659

Author

Roger Bivand

See also

Examples

set_thin_PROJ6_warnings(TRUE) cities <- readOGR(system.file("vectors", package = "rgdal")[1], "cities")
#> OGR data source with driver: ESRI Shapefile #> Source: "/tmp/Rtmpu1yWGf/temp_libpathfa5c0298539de/rgdal/vectors", layer: "cities" #> with 606 features #> It has 4 fields #> Integer64 fields read as strings: POPULATION
is.na(cities$POPULATION) <- cities$POPULATION == -99 summary(cities$POPULATION)
#> Length Class Mode #> 606 character character
td <- file.path(tempdir(), "rgdal_examples"); dir.create(td) # BDR 2016-12-15 (MapInfo driver fails writing to directory with ".") if(nchar(Sys.getenv("OSGEO4W_ROOT")) > 0) { OLDPWD <- getwd() setwd(td) td <- "." } writeOGR(cities, td, "cities", driver="ESRI Shapefile") try(writeOGR(cities, td, "cities", driver="ESRI Shapefile"))
#> Error in writeOGR(cities, td, "cities", driver = "ESRI Shapefile") : #> layer exists, use a new layer name
writeOGR(cities, td, "cities", driver="ESRI Shapefile", overwrite_layer=TRUE) cities2 <- readOGR(td, "cities")
#> OGR data source with driver: ESRI Shapefile #> Source: "/tmp/RtmpU1WIbP/rgdal_examples", layer: "cities" #> with 606 features #> It has 4 fields
summary(cities2$POPULATION)
#> Length Class Mode #> 606 character character
if ("SQLite" %in% ogrDrivers()$name) { tf <- tempfile() try(writeOGR(cities, tf, "cities", driver="SQLite", layer_options="LAUNDER=NO")) } if ("GeoJSON" %in% ogrDrivers()$name) { js <- '{ "type": "MultiPolygon", "coordinates": [[[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]] }' spdf <- readOGR(js, layer='OGRGeoJSON') in1_comms <- sapply(slot(spdf, "polygons"), comment) print(in1_comms) tf <- tempfile() writeOGR(spdf, tf, "GeoJSON", driver="GeoJSON") #spdf1 <- readOGR(tf, "GeoJSON") spdf1 <- readOGR(tf) in2_comms <- sapply(slot(spdf1, "polygons"), comment) print(in2_comms) print(isTRUE(all.equal(in1_comms, in2_comms))) }
#> OGR data source with driver: GeoJSON #> Source: "{ #> "type": "MultiPolygon", #> "coordinates": [[[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], #> [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], #> [100.0, 0.0]]]] #> }", layer: "OGRGeoJSON" #> with 1 features #> It has 0 fields #> [1] "0 0" #> OGR data source with driver: GeoJSON #> Source: "/tmp/RtmpU1WIbP/filefad193cb42051", layer: "GeoJSON" #> with 1 features #> It has 1 fields #> [1] "0 0" #> [1] TRUE
if (FALSE) if ("GML" %in% ogrDrivers()$name) { airports <- try(readOGR(system.file("vectors/airports.gml", package = "rgdal")[1], "airports")) if (class(airports) != "try-error") { writeOGR(cities, paste(td, "cities.gml", sep="/"), "cities", driver="GML") cities3 <- readOGR(paste(td, "cities.gml", sep="/"), "cities") } } # The GML driver does not support coordinate reference systems if ("KML" %in% ogrDrivers()$name) { data(meuse) coordinates(meuse) <- c("x", "y") proj4string(meuse) <- CRS("+init=epsg:28992") meuse_ll <- spTransform(meuse, CRS("+proj=longlat +datum=WGS84")) writeOGR(meuse_ll["zinc"], paste(td, "meuse.kml", sep="/"), "zinc", "KML") } list.files(td)
#> [1] "cities.dbf" "cities.prj" "cities.shp" "cities.shx" "meuse.kml"
roads <- readOGR(system.file("vectors", package = "rgdal")[1], "kiritimati_primary_roads")
#> OGR data source with driver: ESRI Shapefile #> Source: "/tmp/Rtmpu1yWGf/temp_libpathfa5c0298539de/rgdal/vectors", layer: "kiritimati_primary_roads" #> with 35 features #> It has 1 fields
summary(roads)
#> Object of class SpatialLinesDataFrame #> Coordinates: #> min max #> x 667587.7 704048.0 #> y 187716.6 226051.2 #> Is projected: TRUE #> proj4string : #> [+proj=utm +zone=4 +datum=WGS84 +units=m +no_defs] #> Data attributes: #> Id #> Min. :0 #> 1st Qu.:0 #> Median :0 #> Mean :0 #> 3rd Qu.:0 #> Max. :0
if (strsplit(getGDALVersionInfo(), " ")[[1]][2] < "2") { # For GDAL >= 2, the TAB driver may need a BOUNDS layer option writeOGR(roads, td, "roads", driver="MapInfo File") roads2 <- readOGR(paste(td, "roads.tab", sep="/"), "roads") summary(roads2) } scot_BNG <- readOGR(system.file("vectors", package = "rgdal")[1], "scot_BNG")
#> OGR data source with driver: ESRI Shapefile #> Source: "/tmp/Rtmpu1yWGf/temp_libpathfa5c0298539de/rgdal/vectors", layer: "scot_BNG" #> with 56 features #> It has 13 fields
summary(scot_BNG)
#> Object of class SpatialPolygonsDataFrame #> Coordinates: #> min max #> x 7094.552 468285.5 #> y 529495.039 1218342.5 #> Is projected: TRUE #> proj4string : #> [+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 #> +y_0=-100000 +ellps=airy +units=m +no_defs] #> Data attributes: #> SP_ID NAME ID_x COUNT #> Length:56 Length:56 Min. : 1.00 Min. : 0.000 #> Class :character Class :character 1st Qu.:14.75 1st Qu.: 4.750 #> Mode :character Mode :character Median :28.50 Median : 8.000 #> Mean :28.50 Mean : 9.571 #> 3rd Qu.:42.25 3rd Qu.:11.000 #> Max. :56.00 Max. :39.000 #> SMR LONG LAT PY #> Min. : 0.0 Min. :54.94 Min. :1.430 Min. : 27075 #> 1st Qu.: 49.6 1st Qu.:55.78 1st Qu.:3.288 1st Qu.: 100559 #> Median :111.5 Median :56.04 Median :4.090 Median : 182333 #> Mean :152.6 Mean :56.40 Mean :4.012 Mean : 267498 #> 3rd Qu.:223.0 3rd Qu.:57.02 3rd Qu.:4.730 3rd Qu.: 313845 #> Max. :652.2 Max. :60.24 Max. :6.800 Max. :2316353 #> EXP_ AFF X_COOR Y_COOR #> Min. : 1.100 Min. : 0.000 Min. :112892 Min. : 561163 #> 1st Qu.: 4.050 1st Qu.: 1.000 1st Qu.:256624 1st Qu.: 649520 #> Median : 6.300 Median : 7.000 Median :287577 Median : 681524 #> Mean : 9.575 Mean : 8.661 Mean :288524 Mean : 723127 #> 3rd Qu.:10.125 3rd Qu.:11.500 3rd Qu.:333948 3rd Qu.: 794380 #> Max. :88.700 Max. :24.000 Max. :442244 Max. :1168904 #> ID_y #> Min. : 1.00 #> 1st Qu.:14.75 #> Median :28.50 #> Mean :28.50 #> 3rd Qu.:42.25 #> Max. :56.00
if (strsplit(getGDALVersionInfo(), " ")[[1]][2] < "2") { # For GDAL >= 2, the TAB driver may need a BOUNDS layer option writeOGR(scot_BNG, td, "scot_BNG", driver="MapInfo File") list.files(td) scot_BNG2 <- readOGR(paste(td, "scot_BNG.tab", sep="/"), "scot_BNG", addCommentsToPolygons=FALSE) summary(scot_BNG2) } writeOGR(scot_BNG, td, "scot_BNG", driver="MapInfo File", dataset_options="FORMAT=MIF") list.files(td)
#> [1] "cities.dbf" "cities.prj" "cities.shp" "cities.shx" "meuse.kml" #> [6] "scot_BNG.mid" "scot_BNG.mif"
scot_BNG3 <- readOGR(paste(td, "scot_BNG.mif", sep="/"), "scot_BNG")
#> OGR data source with driver: MapInfo File #> Source: "/tmp/RtmpU1WIbP/rgdal_examples/scot_BNG.mif", layer: "scot_BNG" #> with 56 features #> It has 13 fields
summary(scot_BNG3)
#> Object of class SpatialPolygonsDataFrame #> Coordinates: #> min max #> x 7094.552 468285.5 #> y 529495.039 1218342.5 #> Is projected: TRUE #> proj4string : #> [+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 #> +y_0=-100000 +datum=WGS84 +units=m +no_defs] #> Data attributes: #> SP_ID NAME ID_x COUNT #> Length:56 Length:56 Min. : 1.00 Min. : 0.000 #> Class :character Class :character 1st Qu.:14.75 1st Qu.: 4.750 #> Mode :character Mode :character Median :28.50 Median : 8.000 #> Mean :28.50 Mean : 9.571 #> 3rd Qu.:42.25 3rd Qu.:11.000 #> Max. :56.00 Max. :39.000 #> SMR LONG LAT PY #> Min. : 0.0 Min. :54.94 Min. :1.430 Min. : 27075 #> 1st Qu.: 49.6 1st Qu.:55.78 1st Qu.:3.288 1st Qu.: 100559 #> Median :111.5 Median :56.04 Median :4.090 Median : 182333 #> Mean :152.6 Mean :56.40 Mean :4.012 Mean : 267498 #> 3rd Qu.:223.0 3rd Qu.:57.02 3rd Qu.:4.730 3rd Qu.: 313845 #> Max. :652.2 Max. :60.24 Max. :6.800 Max. :2316353 #> EXP_ AFF X_COOR Y_COOR #> Min. : 1.100 Min. : 0.000 Min. :112892 Min. : 561163 #> 1st Qu.: 4.050 1st Qu.: 1.000 1st Qu.:256624 1st Qu.: 649520 #> Median : 6.300 Median : 7.000 Median :287577 Median : 681524 #> Mean : 9.575 Mean : 8.661 Mean :288524 Mean : 723127 #> 3rd Qu.:10.125 3rd Qu.:11.500 3rd Qu.:333948 3rd Qu.: 794380 #> Max. :88.700 Max. :24.000 Max. :442244 Max. :1168904 #> ID_y #> Min. : 1.00 #> 1st Qu.:14.75 #> Median :28.50 #> Mean :28.50 #> 3rd Qu.:42.25 #> Max. :56.00
if(nchar(Sys.getenv("OSGEO4W_ROOT")) > 0) { setwd(OLDPWD) }