Skip to contents

ogr2ogr() is a wrapper of the ogr2ogr command-line utility (see https://gdal.org/programs/ogr2ogr.html). This function can be used to convert simple features data between file formats. It can also perform various operations during the process, such as spatial or attribute selection, reducing the set of attributes, setting the output coordinate system or even reprojecting the features during translation. Refer to the GDAL documentation at the URL above for a description of command-line arguments that can be passed in cl_arg.

Usage

ogr2ogr(
  src_dsn,
  dst_dsn,
  src_layers = NULL,
  cl_arg = NULL,
  open_options = NULL
)

Arguments

src_dsn

Character string. Data source name of the source vector dataset.

dst_dsn

Character string. Data source name of the destination vector dataset.

src_layers

Optional character vector of layer names in the source dataset. Defaults to all layers.

cl_arg

Optional character vector of command-line arguments for the GDAL ogr2ogr command-line utility (see URL above).

open_options

Optional character vector of dataset open options.

Value

Logical indicating success (invisible TRUE). An error is raised if the operation fails.

Note

For progress reporting, see command-line argument -progress: Display progress on terminal. Only works if input layers have the "fast feature count" capability.

See also

ogrinfo()

translate() for raster data

Examples

src <- system.file("extdata/ynp_fires_1984_2022.gpkg", package="gdalraster")

# Convert GeoPackage to Shapefile
shp_file <- file.path(tempdir(), "ynp_fires.shp")
ogr2ogr(src, shp_file, src_layers = "mtbs_perims")

# Reproject to WGS84
ynp_wgs84 <- file.path(tempdir(), "ynp_fires_wgs84.gpkg")
args <- c("-t_srs", "EPSG:4326")
ogr2ogr(src, ynp_wgs84, cl_arg = args)

# Clip to a bounding box (xmin, ymin, xmax, ymax in the source SRS)
# This will select features whose geometry intersects the bounding box.
# The geometries themselves will not be clipped unless "-clipsrc" is
# specified.
# The source SRS can be overridden with "-spat_srs" "<srs_def>"
ynp_clip <- file.path(tempdir(), "ynp_fires_aoi_clip.gpkg")
bb <- c(469685.97, 11442.45, 544069.63, 85508.15)
args <- c("-spat", bb)
ogr2ogr(src, ynp_clip, cl_arg = args)

# Filter features by a -where clause
ynp_filtered <- file.path(tempdir(), "ynp_fires_2000_2022.gpkg")
sql <- "ig_year >= 2000 ORDER BY ig_year"
args <- c("-where", sql)
ogr2ogr(src, ynp_filtered, src_layers = "mtbs_perims", cl_arg = args)

deleteDataset(shp_file)
#> [1] TRUE
deleteDataset(ynp_wgs84)
#> [1] TRUE
deleteDataset(ynp_clip)
#> [1] TRUE
deleteDataset(ynp_filtered)
#> [1] TRUE