Crop for SpatialPolygonsDataFrame
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")
how to crop raster based on SpatialPolygons in R
You can use raster::mask
. Here's a reproducible example:
library(raster)
r = raster(vals = rnorm(400), nrows=20, ncols=20, ext= extent(c(0, 20, 0, 20)))
p = Polygon(matrix(5, 5, 15, 12, 7, 16, 3, 10), ncol=2, byrow = T))
p = SpatialPolygons(list(Polygons(list(p), "p")))
plot(r)
lines(p)
r2 = mask(r,p)
plot(r2)
If you also need to clip the extent of the raster to remove empty rows and columns around the mask, then you can either use crop
before applying mask
, or you can use trim(r2, values = NA)
afterwards.
Related Topics
Why (Or When) Is Rscript (Or Littler) Better Than R Cmd Batch
Rselenium: Server Signals Port Is Already in Use
How to Detect Free Variable Names in R Functions
R Solve:System Is Exactly Singular
Bars in Geom_Bar Have Unwanted Different Widths When Using Facet_Wrap
How to Add a Table to a Ggplot
How to Use the 'Sweep' Function
Scale and Size of Plot in Rstudio Shiny
Creating Multi Column Legend in Ggplot
What Does the @ Symbol Mean in R
How to Calculate the Probability for a Given Quantile in R
Merge Dataframes, Different Lengths
Reshaping Data Frame with Duplicates
Pivot_Longer with Multiple Classes Causes Error ("No Common Type")
R V3.4.0-2 Unable to Find Libgfortran.So.3 on Arch