Find maximum extent out of list of shapefiles (in projected coordinate system) in R

Given a list of shapey objects:

> shapes = list(cities, birds)

Compute the list of extents of those shapey objects

> shape_extents = lapply(shapes, raster::extent)

and then call raster::merge on them to get the merged extent:

> do.call(raster::merge, shape_extents)
class      : Extent 
xmin       : -165.27 
xmax       : 177.1302 
ymin       : -53.15 
ymax       : 78.2 

I think that saves you having to do the matrix conversion and then manipulate that.

Note this is flexible, in that it works on any object with an extent method (which includes rasters, sp and sf objects, be they points, lines, polygons or anything else), and minimal, in that it doesn't do any geometry reorganisation or conversion that might slow things down.


The raster::extent() can take SpatialObject as the input (not only (xmin, xmax, ymin, ymax)).

If the input geometries are the same type, extent(union(cities, birds)) should work. However, as the cities are points and the birds are polygons in the provided example, we need a workaround (I would suggest rgeos::gUnion()).

# The CRS have to be the same, but unfortunately birds' CRS is NA.
crs(cities)  # WGS84
crs(birds)   # NA
crs(birds) <- "+proj=longlat +datum=WGS84 +no_defs"

library(rgeos)
e <- as(extent(rgeos::gUnion(cities, birds)), 'SpatialPolygons')
extent(e)
# class      : Extent 
# xmin       : -165.27 
# xmax       : 177.1302 
# ymin       : -53.15 
# ymax       : 78.2 

Next step is the same as the one you have linked to.

crs(e) <- "+proj=longlat +datum=WGS84 +no_defs"
r <- crop(data_to_be_cropped, e)

So if you have some extent objects from your shapefiles (ext1,ext2,ext3...) then you get full extent:

spoly <-  do.call(bind, sapply(c(ext1,ext2,ext3), FUN = function(x){as(x, 'SpatialPolygons')})) 

full_extent <- extent(bbox(spoly))

Tags:

R

Raster

Rgdal