I have to read in a small portion of a huge ESRI shapefile in R. I am doing this in two steps:

Step 1: I use ogr2ogr to clip the shapefile to my bounding box:

ogr2ogr -clipsrc xMin yMin xMax yMax outfile.shp infile.shp

Step 2: I read this into R with rgdal:

df = readOGR(dsn="/path", layer="outfile")

The problem is that I have to do this for multiple files, and it's hard to keep track of the OGR operations which generated each of these separate files. Is there any way to pipe ogr2ogr in R, so that step 1 is done on the fly?

有帮助吗?

解决方案

Try using the system call. Hard to tell without code and data, but you should be able to create a list of either shapefiles to process (if you have multiple shapefiles) or coordinates to process if you have multiple bounding boxes you want to clip from the shapefile.

work.dir <- "C:/Program Files (x86)/FWTools2.4.7/bin" # use your FWTools location
setwd(work.dir)
out.shape.file <- "foo2.shp"
in.shape.file <- "foo1.shp"
x.min <- 100
y.min <- 100
x.max <- 200
y.max <- 200
system(paste("ogr2ogr -clipsrc", x.min, y.min, x.max, y.max, 
      out.shape.file, in.shape.file))

其他提示

Note that you can clip with the rgeos package, something like this (I use raster to make creating a simple mask polygon easy):

library(rgeos)
library(raster)
library(rgdal)
## as per your example
df = readOGR(dsn="/path", layer="outfile")
## create a simple polygon layer and intersect
res <- gIntersection(df, as(extent(x.min, x.max, ymin, y.max), "SpatialPolygons"), byid = TRUE)

That might not work exactly as is, but could be worth exploring if reading the entire shapefile is not a problem.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top