Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop for SpatialPolygonsDataFrame

Tags:

r

crop

spatial

I have two SpatialPolygonsDataFrame files: dat1, dat2

extent(dat1) class       : Extent  xmin        : -180  xmax        : 180  ymin        : -90  ymax        : 90    extent(dat2) class       : Extent  xmin        : -120.0014  xmax        : -109.9997  ymin        : 48.99944  ymax        : 60  

I want to crop the file dat1 using the extent of dat2. I don't know how to do it. I just handle raster files using "crop" function before.

When I use this function for my current data, the following error occurs:

> r1 <- crop(BiomassCarbon.shp,alberta.shp) Error in function (classes, fdef, mtable)  :    unable to find an inherited method for function ‘crop’ for signature"SpatialPolygonsDataFrame"’ 
like image 719
Jian Zhang Avatar asked Dec 21 '12 00:12

Jian Zhang


1 Answers

Streamlined method added 2014-10-9:

raster::crop() can be used to crop Spatial* (as well as Raster*) objects.

For example, here's how you might use it to crop a SpatialPolygons* object:

## Load raster package and an example SpatialPolygonsDataFrame library(raster)  data("wrld_simpl", package="maptools")  ## Crop to the desired extent, then plot out <- crop(wrld_simpl, extent(130, 180, 40, 70)) plot(out, col="khaki", bg="azure2") 

Original (and still functional) answer:

The rgeos function gIntersection() makes this pretty straightforward.

Using mnel's nifty example as a jumping off point:

library(maptools) library(raster)   ## To convert an "Extent" object to a "SpatialPolygons" object. library(rgeos) data(wrld_simpl)  ## Create the clipping polygon CP <- as(extent(130, 180, 40, 70), "SpatialPolygons") proj4string(CP) <- CRS(proj4string(wrld_simpl))  ## Clip the map out <- gIntersection(wrld_simpl, CP, byid=TRUE)  ## Plot the output plot(out, col="khaki", bg="azure2") 

enter image description here

like image 65
Josh O'Brien Avatar answered Sep 20 '22 17:09

Josh O'Brien